How to use decodeIfPresent for all properties of a Codable?

Viewed 520

How do I make a Codable class use decodeIfPresent for all properties without needing to type out all properties in a custom initializer?

An example:

class Book: Codable {
    var name: String = "Default name"
    var pages: Int = 1

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        for key in container.allKeys {
            // What to do here to call decodeIfPresent?
        }
    }
}

In essence, I'd like to replicate the automatically created initializer myself, making this one change to how it works.

1 Answers

Apparently this is not possible at this time (Swift 4). This is because Swift does not support setting a property dynamically by name.

Related