Skip to content

Instantly share code, notes, and snippets.

@DhavalDobariya86
Last active April 11, 2020 20:16
Show Gist options
  • Save DhavalDobariya86/b1459966b88a748b6980a4655e8d5652 to your computer and use it in GitHub Desktop.
Save DhavalDobariya86/b1459966b88a748b6980a4655e8d5652 to your computer and use it in GitHub Desktop.
Codable with renamed parameters
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