Skip to content

Instantly share code, notes, and snippets.

@DhavalDobariya86
Created April 11, 2020 20:27
Show Gist options
  • Save DhavalDobariya86/514b8c6f7db3857ca0507c2c2b82f9c6 to your computer and use it in GitHub Desktop.
Save DhavalDobariya86/514b8c6f7db3857ca0507c2c2b82f9c6 to your computer and use it in GitHub Desktop.
Codable to handle optional properties from JSON
import UIKit
struct Employee: Codable {
let name: String
let phoneNumber: String?
}
let jsonDataWithPhoneNumber: Data = """
{
"name": "Eric",
"phoneNumber": "+1 12312312"
}
""".data(using: .utf8)!
let jsonDataWithoutPhoneNumber: Data = """
{
"name": "Ronaldo"
}
""".data(using: .utf8)!
let eric = try! JSONDecoder().decode(Employee.self, from: jsonDataWithPhoneNumber)
let ronaldo = try! JSONDecoder().decode(Employee.self, from: jsonDataWithoutPhoneNumber)
let notAvailable = "Not Available"
print("Eric phone number = \(eric.phoneNumber ?? notAvailable)")
print("Ronaldo phone number = \(ronaldo.phoneNumber ?? notAvailable)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment