I have a generic struct allowing different types to be used. I do not want to constrain the whole struct to only Decodable items.
What is the best way to fix the following error, where I try to only execute some code if T conforms to Decodable:
Instance method '...' requires that 'T' conform to 'Decodable'
struct Something<T> {
...
func item<T>(from data: Data) -> T? where T: Decodable {
try? JSONDecoder().decode(T.self, from: data)
}
func getter() -> T {
let value = ...
if let value = value as? T { return value } // something simple like string
if let data = value as? Data, T.self is Decodable { // something complex
return item(from: data) ?? defaultValue // error is thrown here
}
return defaultValue
}
}
As you can see I'm checking the conformance with the if-clause, but that isn't enough to access the constrained method? :/