I am working on a project that has a network client that basically follows the below pattern.
protocol EndpointType {
var baseURL: String { get }
}
enum ProfilesAPI {
case fetchProfileForUser(id: String)
}
extension ProfilesAPI: EndpointType {
var baseURL: String {
return "https://foo.bar"
}
}
protocol ClientType: class {
associatedtype T: EndpointType
func request(_ request: T) -> Void
}
class Client<T: EndpointType>: ClientType {
func request(_ request: T) -> Void {
print(request.baseURL)
}
}
let client = Client<ProfilesAPI>()
client.request(.fetchProfileForUser(id: "123"))
As part of tidying up this project and writing tests I have found the it is not possible to inject a client when conforming to the ClientType protocol.
let client: ClientType = Client<ProfilesAPI>() produces an error:
error: member 'request' cannot be used on value of protocol type 'ClientType'; use a generic constraint instead
I would like to maintain the current pattern ... = Client<ProfilesAPI>()
Is it possible to achieve this using type erasure? I have been reading but am not sure how to make this work.
clientClient<RolesAPI>()and so on.client.request(.fetchProfileForUser(id: "123"))with the enum value withinrequest(...)being set using a case from an enum that conforms toEndpointType. That enum is set when the instance ofclientis declared.