Skip to content

Instantly share code, notes, and snippets.

@popochess
Last active March 28, 2018 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save popochess/eb3cf6df5e227975421a312dff1ccd2c to your computer and use it in GitHub Desktop.
Save popochess/eb3cf6df5e227975421a312dff1ccd2c to your computer and use it in GitHub Desktop.
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