How to use both JSONDecoder on a generic type that isn't explicitly conform to the Codable protocol?

Hello! I would like to know if there's a way to use JSONDecoder() encode/decode on a generic type that doesn't explicitly conform to the Codable protocol.

Let's say I have this initializer in which I receive a function that returns a generic type:
convenience init<T>(_: (T) -> T) {}
This generic type can be conformable to the protocol Codable or can't be because I don't have access to the function passed since this is a library.

I can retrieve if the generic type T conforms to Codable with:
if T.self is Codable.Type { use JSONDecoder() } else { use JSONSerialization }

For the else condition everything works fine since JSONSerialization doesn't require any protocol but for the JSONDecoder part, I don't know how to make T explicitly conformable to the Codable protocol inside the init.

Of course, the first solution that came to my mind was overloading. But I already have many convenience initializers so I would like to know if there's another way to achieve this.

You could make two functions, one of which is constrained to T: Codable.

Yes in fact overloading was my first solution. But I’m wondering if there’s another solution that implies having only one function.

Terms of Service

Privacy Policy

Cookie Policy