1

I have following simple protocol:

protocol JSONParser {

   associatedtype JSONResult
   func parse<T: Codable>(response: Response, type: T) -> JSONResult

}

Function parse takes simple Response which is struct and takes T which is Codable. And here is how I implement this protocol:

struct AuthJSONParser: JSONParser {

    func parse<T: Codable>(response: Response, type: T) -> AuthResult<T> {

    }

}

It seems everything okay. But Xcode says that it does not conform to protocol. Here AuthResult<T> just for case:

enum AuthResult<Model: Codable> {
   case success(data: Model)
   case failed(msg: String)
}

I can't figure out what is wrong with my implementation. I want to use generic functions, instead of generic structs.

neo
  • 1,314
  • 2
  • 14
  • 34
  • AuthJSONParser.parse has to return a concrete type. There are a number of ways to address this, but it depends on your needs. Does AuthResult have to be generic? Can AuthJSONParser be generic? Whys is the parse method generic parameter `T` the same as the return value generic parameter `T`? – Rob C Apr 30 '20 at 05:33
  • I think `AuthJSONParser` has a concrete return type. It returns `AuthResult` where `T` is `Codable`. Why does it have number of ways to address? 1) Yes, `AuthResult` should be generic. 2) I want to avoid `AuthJSONParser` to be generic. If it would be generic, then I would create different instances of it to each type. 3) It takes `T` which is some struct that confirms to `Codable`. `AuthResult` where `T` is also codable. They are the same. – neo Apr 30 '20 at 05:45
  • Notice that if you have a return type of AuthResult your compilation error goes away. That's one way to address the problem. Another solution is to make AuthJSONParser a generic struct. – Rob C Apr 30 '20 at 05:47
  • You mean that `String` does not confirm to `Codable` and anyways compiler doesn't warn? – neo Apr 30 '20 at 05:50
  • String does conform to Codable. And right, if you specify the generic parameter type of AuthResult the compiler does not complain. – Rob C Apr 30 '20 at 05:52

0 Answers0