Best way to bypass compile error for <T: Codable>?

I have a JsonSerializer protocol which should support JsonSerialization (Swift < 4.0) and JSONEncoder/ JSONDecoder (Swift >= 4.0).

In protocol, there's a function called toDict<T>(withNil value: String) -> [String : T]?. However, if I'd like to use JsonDecoder here, I have to make T: Decodable which doesn't make sense here since JsonSerialization doesn't require T to conform to Decodable. Is there any better way to solve this kind of compile error? Thanks

Why do you need to support Swift < 4?

How about providing an overload?

func toDict<T>(withNil value: String) -> [String : T]?
func toDict<T: Decodable>(withNil value: String) -> [String : T]?
1 Like

might not need to support Swift < 4. it's more like to proovide an option for user to choose its own serializer. Ex: SwiftyJSON

It might be a good option if compiler error can't be overcome

Another option might be to define two protocols with different toDict signatures using #if checks:

#if compiler(<4.0)
  protocol JsonSerializer {
    func toDict<T>(withNil value: String) -> [String : T]?
  }
#else
  protocol JsonSerializer {
    func toDict<T>(withNil value: String) -> [String : T]?
    func toDict<T: Decodable>(withNil value: String) -> [String : T]?
  }
#endif
Terms of Service

Privacy Policy

Cookie Policy