I'm running into what I think is a type-erasure issue that's described here. However, I'm having a hard time wrapping my head around the solve. There's some mention of "Opening Existentials" in this swift repository solving this here, but I'm not totally sure how to apply that in my situation.
Here's an example situation: I'm experimenting with the idea of a generic "getter" for fetching various services in my app. This will help clean up the interface and hopefully be a bit more scalable as more services get added. However, there are some issues that I described above.
protocol Service { }
protocol TestClient: Service {
func fetchData() -> Data
}
class TestClientImpl: TestClient {
func fetchData() -> Data {
return Data()
}
}
protocol SecondTestClient: Service {
func fetchDifferentData() -> Data
}
class SecondTestClientImpl: SecondTestClient {
func fetchDifferentData() -> Data {
return Data()
}
}
class ServiceFetcher {
let services: [Service] = [TestClientImpl(), SecondTestClientImpl()]
func getService<T: Service>() -> T? {
for service in services {
if let finalService = service as? T {
return finalService
}
}
return nil
}
}
let serviceFetcher = ServiceFetcher()
let testClient: TestClient? = serviceFetcher.getService() // error: Type 'any TestClient' cannot conform to 'Service'
Any advice would be appreciated, thanks in advance!