I have a protocol for simple http client:
protocol HttpClientProtocol {
func request(route: any RouteProtocol)
}
protocol RouteProtocol {
associatedtype T : Encodable //this is probably irrelevant, but nevertheless
// ...stuff
}
Now, I'm trying to use this protocol as a type that will be used by clients (e.g. some MyThingRepository will inject HttpClientProtocol without knowing the specific type that will be injected - for loose coupling). Then I'm trying to create a concrete class from that protocol.
class ApiClient : HttpClientProtocol {
func request(route: any ApiRouteProtocol) {
//... use specific ApiRouteProtocol here, not the general RouteProtocol
}
}
protocol ApiRouteProtocol : RouteProtocol, URLRequestConvertible { }
Problem is that I get Type 'ApiClient' does not conform to protocol 'HttpClientProtocol' compilation error.
My intuition is that if the protocol allows any RouteProtocol, then the class implementing it should be able to narrow down the type to ApiRouteProtocol. However, the compiler doesn't agree. Is my intuition wrong or is it a Swift limitation?
What could I do to work around it? My only working idea for now is to force cast the route to ApiRouteProtocol in ApiClient.