Search code examples
swiftcodabledecodable

When to use CodingKeys in Decodable(Swift)


Let's say I want to decode a Person struct as follows.

struct Person: Decodable {

let firstName: String
let lastName: String
let age: Int: String
}

I understand that the data can be decoded only with above. Therefore if I'm not changing the properties to a custom name if there no difference between the above and below implementation?

Further is there other cases where you want to use CodingKeys? I'm confused when they are necessary other than for renaming purposes.

struct Person: Decodable {

let firstName: String
let lastName: String
let age: Int: String
}

enum CodingKeys: String, CodingKey {
        
        case firstName
        case lastName
        case age
}


Solution

  • First of all there is a make-or-break rule for using CodingKeys:

    • You can omit CodingKeys completely if the JSON – or whatever Codable conforming format – keys match exactly the corresponding properties (like in your example) or the conversion is covered by an appropriate keyDecodingStrategy.

    • Otherwise you have to specify all CodingKeys you need to be decoded (see also reason #3 below).


    There are three major reasons to use CodingKeys:

    1. A Swift variable/property name must not start with a number. If a key does start with a number you have to specify a compatible CodingKey to be able to decode the key at all.
    2. You want to use a different property name.
    3. You want to exclude keys from being decoded for example an id property which is not in the JSON and is initialized with an UUID constant.

    And CodingKeys are mandatory if you implement init(from decoder to decode a keyed container.