Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use CodingKeys in Decodable

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
}
like image 440
mendokusai Avatar asked Aug 27 '26 16:08

mendokusai


2 Answers

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: Decoder) to decode a keyed container.

like image 131
vadian Avatar answered Aug 30 '26 12:08

vadian


You can use CodingKeys in different ways for example, when you know that at least one of the name of values that you are expecting in your JSON is actually different from your "let or var" name.

Example:

struct Person: Decodable {

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

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

Other case is when you are using class inheritance.

In conclusion, if you are absolutely sure that you are using the same variable name as your encoding key(JSON), you can omit it (but if you want to put it, it doesn't matter), but if there's a difference, maybe a change of your codingKeys like an uppercase or using different words, you should use the enum to map the correct key with the variable name.

like image 45
DianaRojas Avatar answered Aug 30 '26 11:08

DianaRojas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!