How to use custom names for Swift properties when decoding JSON data
Learn to use Swift's CodingKey protocol.
20 Feb 2023 · 2 min read
Swift's Codable protocol makes it easy to convert JSON data to native Swift types and the other way around. In some cases though, we might need a more customized solution, for example to name Swift properties differently than the JSON keys or to ignore some properties.
Let's look at how to do that.

Codable types allow to declare a nested enumeration named CodingKeys that conforms to the CodingKey protocol. When we do that, the enum cases represent the properties that need to be included. The names of the enumeration cases should match the names we gave to the corresponding properties.
Let's say, we get the following JSON response from the server:
{"username" : "tanaschita","validated": true}
And we'd like to map it to the following User struct:
struct User: Codable {let username: Stringlet isValidated: Bool}
To map JSON's validated to the isValidated property of the User struct, we can use the mentioned CodingKey protocol as follows:
struct User: Codable {let username: Stringlet isValidated: Boolenum CodingKeys: String, CodingKey {case usernamecase isValidated = "validated"}}
By specifying raw-values, we control which JSON properties are assigned to which properties of our custom Swift types.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips