Last active
April 11, 2020 20:16
-
-
Save DhavalDobariya86/b1459966b88a748b6980a4655e8d5652 to your computer and use it in GitHub Desktop.
Codable with renamed parameters
This file contains 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 Country: Codable { | |
let name: String | |
let capital: String | |
let alternateSpellings: [String] | |
enum CodingKeys: String, CodingKey { | |
case name | |
case capital | |
// Map `altSpellings` from JSON to proper property name `alternateSpellings` | |
case alternateSpellings = "altSpellings" | |
} | |
} | |
let jsonData: Data = """ | |
{ | |
"name": "United States of America", | |
"capital": "Washington, D.C.", | |
"callingCodes": ["1"], | |
"region": "Americas", | |
"subregion": "Northern America", | |
"population": 323947000, | |
"area": 9629091, | |
"borders": ["CAN", "MEX"], | |
"altSpellings": ["US", "USA","United States of America"] | |
} | |
""".data(using: .utf8)! | |
let country = try! JSONDecoder().decode(Country.self, from: jsonData) | |
print("Country alternate spellings: \(country.alternateSpellings)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment