I have the following struct
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool
var version: Int64
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
However, I'm getting compiler error
Type 'Checklist' does not conform to protocol 'Decodable'
The only way I can solve, is by changing the excluded properties, into Optional.
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool?
var version: Int64?
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
May I know why this is so? Is this the only right way to resolve such compiler error?
They need not be optionals, but they must have some initial value, e.g.
struct Checklist : Codable {
let id: Int64
var text: String?
var checked: Bool
var visible: Bool = false
var version: Int64 = 0
private enum CodingKeys: String, CodingKey {
case id
case text
case checked
}
}
Otherwise those properties would be undefined when an instance is created from an external representation, via the synthesized
init(from decoder: Decoder)
method. Alternatively you can implement that method yourself, ensuring that all properties are initialized.
Optionals have an implicit initial value of nil
, that's why your solution works as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With