Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Codable with reserved word

Tags:

swift

codable

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

like image 674
Bryan Deemer Avatar asked Jul 05 '18 13:07

Bryan Deemer


2 Answers

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

var `extension`: String
like image 132
Papershine Avatar answered Oct 21 '22 19:10

Papershine


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.

like image 31
StartPlayer Avatar answered Oct 21 '22 21:10

StartPlayer