Created
April 11, 2020 20:27
-
-
Save DhavalDobariya86/514b8c6f7db3857ca0507c2c2b82f9c6 to your computer and use it in GitHub Desktop.
Codable to handle optional properties from JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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