Home > AI > Language > Swift >

CodingKey

change the key in the Codable object.

import Foundation

struct Address : Codable {

    var street: String
    var zip: String
    var city: String
    var state: String

    private enum CodingKeys : String, CodingKey {
        case street, zip = "zip_code", city, state
    }
}


let address = Address(street: "Apple Bay Street",
                      zip: "94608",
                      city: "Emeryville",
                      state: "California")

do {
    let encoded = try JSONEncoder().encode(address)
    print(String(decoding: encoded, as: UTF8.self))
} catch {
    print(error)
}

Leave a Reply