Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42710

If I want to exclude some properties from Codable, why those properties must be Optional?

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?

Upvotes: 4

Views: 610

Answers (1)

Martin R
Martin R

Reputation: 539775

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.

Upvotes: 6

Related Questions