I am trying to encode/decode JSON data, and I have the following code:
struct SomeOrdinaryClass: Decodable {
// ...
}
struct SomeBox<T>: Decodable {
var data: T?
}
But Xcode gives me the following error:
myfile.swift:16:8 Type 'SomeBox' does not conform to protocol 'Decodable'
Is there anyway to overcome this?
You're almost there…
In order to synthesize Decodable
conformance for your SomeBox
type, the compiler requires that each of its stored properties must conform to Decodable
too. This isn't true of your generic type T
— it could be anything.
Instead, you should also constrain T
to Decodable
:
struct SomeBox<T: Decodable>: Decodable {
var data: T?
}
or equivalently:
struct SomeBox<T>: Decodable where T: Decodable {
var data: T?
}