Search code examples
swiftcodable

When decoding a Codable struct from JSON, how do you initialize a property not present in the JSON?


Say that in this example here, this struct

struct Reminder: Identifiable {
    var id: String = UUID().uuidString
    var title: String
    var dueDate: Date
    var notes: String? = nil
    var isComplete: Bool = false
}

is instead decoded from JSON array values (rather than constructed like in the linked example). If each JSON value were to be missing an "id", how would id then be initialized? When trying this myself I got an error keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil)).


Solution

  • You can simply use coding keys, like this:

    struct Reminder: Identifiable, Codable {
        var id: String = UUID().uuidString
        var title: String
        var dueDate: Date
        var notes: String? = nil
        var isComplete: Bool = false
        
        enum CodingKeys: String, CodingKey {
            case title
            case dueDate
            case notes
            case isComplete
        }
    }
    

    That way, the only properties that will be encoded/decoded are the ones that have a corresponding coding key.