0

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 :)

2
  • I think that the issue is that your are using Decodable as an existential type in askedDecodableApiResult. An existential type of a protocol may not conform to the protocol itself, e.g. the Decodable existential type does not conform to the Decodable protocol while the complete function expect it to be Decodable. Try to avoid using an existential type in askedDecodableApiResult. Use a concrete Decodable type instead. Commented Jun 15, 2022 at 8:46
  • 1
    @LouisLac, your answer was totally correct. But as I couldn't use a concrete Decodable type, and after a long workaround with colleagues, I ended using the trick below : 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 :) Commented Jun 15, 2022 at 13:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.