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
Just add backticks to the variable name to make the compiler think that it's a variable, not a keyword.
var `extension`: String
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With