CodingKeys for Renaming
Map differing JSON and property names.
Why Rename Keys?
JSON APIs often use names that differ from your Swift property names — first_name vs firstName. A CodingKeys enum bridges the two without changing your model's API.
import Foundation
struct User: Codable {
var firstName: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
}
}
print("CodingKeys maps firstName to first_name")Anatomy of CodingKeys
CodingKeys is a nested enum that conforms to String, CodingKey. Each case matches a property name; its raw value is the JSON key to use.
import Foundation
struct Product: Codable {
var productName: String
var unitPrice: Double
enum CodingKeys: String, CodingKey {
case productName = "product_name"
case unitPrice = "unit_price"
}
}
print(Product.CodingKeys.productName.rawValue)