Search code examples
swiftcodable

Swift Codable with reserved word


I have a situation where the JSON being returned from an API has a field named extension, which is a reserved word in Swift. My codable is blowing up when I try to use it.

I've searched for the last two hours, but I can't seem to find any solution.

Has anyone run into this before:

public struct PhoneNumber: Codable {

    var phoneNumber: String
    var extension: String
    var isPrimary: Bool
    var usageType: Int
}

Keyword 'extension' cannot be used as an identifier here


Solution

  • I've had similar problems with 'return'. You can get around with CodingKeys.

    public struct PhoneNumber: Codable {
        enum CodingKeys: String, CodingKey {
            case phoneNumber
            case extensionString = "extension"
            case isPrimary
            case usageType
        }
    
      var phoneNumber: String
      var extensionString: String
      var isPrimiry: Bool
      var usageType: Int
    }
    

    As you cant call a property 'extension' you name it something similar but use the CodingKeys to tell you object what the key in the JSON is.