Last active
April 11, 2020 20:12
-
-
Save DhavalDobariya86/9b44bb519ac9893c585b36c3945b9922 to your computer and use it in GitHub Desktop.
Simple use of Codable to encode/decode 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 Country: Codable { | |
let name: String | |
let capital: String | |
let callingCodes: [String] | |
let population: Double | |
let area: Double | |
let borders: [String] | |
let region: String | |
let subregion: String | |
} | |
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"] | |
} | |
""".data(using: .utf8)! | |
let country = try! JSONDecoder().decode(Country.self, from: jsonData) | |
print("Country name = \(country.name)") | |
print("Country capital = \(country.capital)") | |
print("Country sub region = \(country.subregion)") | |
print("Country borders = \(country.borders.description)") | |
print("Country population = \(country.population)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment