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
}
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
:
CodingKey
to be able to decode the key at all.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.