Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

codable

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?

like image 693
Cheok Yan Cheng Avatar asked Sep 03 '25 03:09

Cheok Yan Cheng


1 Answers

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.

like image 75
Martin R Avatar answered Sep 07 '25 09:09

Martin R