Home > Enterprise >  When to use CodingKeys in Decodable(Swift)
When to use CodingKeys in Decodable(Swift)

Time:11-02

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
}

CodePudding user response:

Therefore if I'm not changing the properties to a custom name if there no difference between the above and below implementation?

Yes, but there's a bit of misunderstanding here. The two implementations you have are literally identical because in the second one the CodingKeys enum would never be used. To be used, the enum must be nested within the Decodable conforming type (Person in this case):

struct Person: Decodable {
    let firstName: String
    let lastName: String
    let age: Int

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

There is in practice no difference between this implementation and the ones you provided.


Further is there other cases where you want to use CodingKeys?

CodingKeys are not used solely by Decodable, they are also used by Encodable. When using Encodable, a reason to use CodingKeys is to specify only a subset of the instances fields should be serialized.

CodePudding user response:

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.

  • Related