I'm writing some tests and mocks for my product but I'm having troubles with generic parameters and constraints...
enum ApiResult<Success, Failure> where Failure: Error {
case success(Success)
case failure(Failure)
case disconnected
}
var askedDecodableApiResult: ApiResult<Decodable, Error> = .disconnected
func complete<T>(callback: @escaping (ApiResult<T, Error>) -> Void) where T: Decodable {
callback(askedDecodableApiResult) // 💥 Cannot convert value of type 'ApiResult<Decodable, Error>' to expected argument type 'ApiResult<T, Error>'
}
I'm lost with that error. What should I do to be able to send in my callback the pre-defined answer ? In the end, I want to be able to give my askedDecodableApiResult any ApiResult sporting a value that either inherits from Decodable or inherits from Error.
I need your help, thanks in advance :)
Decodableas an existential type inaskedDecodableApiResult. An existential type of a protocol may not conform to the protocol itself, e.g. theDecodableexistential type does not conform to theDecodableprotocol while thecompletefunction expect it to beDecodable. Try to avoid using an existential type inaskedDecodableApiResult. Use a concreteDecodabletype instead.askedDecodableApiResultis now of type Any and I do the cast inside the method. If it can't be casted, it can crash as it is for tests only and it would mean I made a mistake in my test code. Anyway, thank you for your answer :)