Created
July 20, 2018 07:15
-
-
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
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 | |
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