Last active
March 28, 2018 16:10
-
-
Save popochess/eb3cf6df5e227975421a312dff1ccd2c to your computer and use it in GitHub Desktop.
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 Foundation | |
let json = """ | |
[ | |
{ | |
"product_name": "Bananas", | |
"product_cost": 200, | |
"description": "A banana grown in Ecuador." | |
}, | |
{ | |
"product_name": "Oranges", | |
"product_cost": 100, | |
"description": "A juicy orange." | |
} | |
] | |
""".data(using: .utf8)! | |
struct GroceryProduct: Codable { | |
var name: String | |
var points: Int | |
var description: String? | |
private enum CodingKeys: String, CodingKey { | |
case name = "product_name" | |
case points = "product_cost" | |
case description | |
} | |
} | |
let decoder = JSONDecoder() | |
let products = try decoder.decode([GroceryProduct].self, from: json) | |
print("The following products are available:") | |
for product in products { | |
print("\t\(product.name) (\(product.points) points)") | |
if let description = product.description { | |
print("\t\t\(description)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment