8

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

Bryan Deemer
  • 743
  • 1
  • 6
  • 18

2 Answers2

17

Just add backticks to the variable name to make the compiler think that it's a variable, not a keyword.

var `extension`: String
Papershine
  • 4,995
  • 2
  • 24
  • 48
12

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.

StartPlayer
  • 485
  • 4
  • 21