Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created July 20, 2018 07:15
Show Gist options
  • Save derekli66/e5f697047da60e52572c0aff33e0276a to your computer and use it in GitHub Desktop.
Save derekli66/e5f697047da60e52572c0aff33e0276a to your computer and use it in GitHub Desktop.
Decodable protocol implementation practice. Refer to https://developer.apple.com/documentation/foundation/jsondecoder
import Foundation
import AppKit
struct GroceryProduct: Decodable {
var name: String
var points: Int
var description: String?
enum CodingKeys: String, CodingKey {
case name = "Name"
case points = "Points"
case description = "Description"
}
}
let json = """
{
"Name": "Durian",
"Points": 600,
"Description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name) // Prints "Durian"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment