Skip to content

Instantly share code, notes, and snippets.

@sebastienwindal
Last active January 27, 2020 23:49
Show Gist options
  • Save sebastienwindal/834a3106101409e9a43cfa54e34b0747 to your computer and use it in GitHub Desktop.
Save sebastienwindal/834a3106101409e9a43cfa54e34b0747 to your computer and use it in GitHub Desktop.
import Foundation
import Tagged
struct Product: Codable {
let id: ProductID
let descr: String
typealias ProductID = Tagged<Product, UUID>
}
struct Inventory: Codable {
let products: [Product]
let promotedProductID: Product.ProductID
}
struct TaggedJSONData {
static let inventoryJSON: String = """
{
"products": [
{
"id": "0B3DBF1A-EE56-41F5-8666-16CA8DAFD03F",
"descr": "Silver Fork"
},
{
"id": "CF66A6B3-2D17-4B87-8C9A-C1700C083EE9",
"descr": "Wooden spoon"
},
{
"id": "F6A85945-9B6D-44EB-A9A8-FD68A8161790",
"descr": "Plastic knife"
}
],
"promotedProductID": "CF66A6B3-2D17-4B87-8C9A-C1700C083EE9"
}
"""
static func parseJSON() -> Inventory {
guard let data = inventoryJSON.data(using: .utf8) else {
fatalError("bad json string bro")
}
let jsonDecoder = JSONDecoder()
guard let obj = try? jsonDecoder.decode(Inventory.self, from: data) else {
fatalError("bad json data bro")
}
return obj
}
}
/*
let inventory = TaggedJSONData.parseJSON()
result:
(lldb) po inventory
▿ Inventory
▿ products : 3 elements
▿ 0 : Product
▿ id : 0B3DBF1A-EE56-41F5-8666-16CA8DAFD03F
- rawValue : 0B3DBF1A-EE56-41F5-8666-16CA8DAFD03F
- descr : "Silver Fork"
▿ 1 : Product
▿ id : CF66A6B3-2D17-4B87-8C9A-C1700C083EE9
- rawValue : CF66A6B3-2D17-4B87-8C9A-C1700C083EE9
- descr : "Wooden spoon"
▿ 2 : Product
▿ id : F6A85945-9B6D-44EB-A9A8-FD68A8161790
- rawValue : F6A85945-9B6D-44EB-A9A8-FD68A8161790
- descr : "Plastic knife"
▿ promotedProductID : CF66A6B3-2D17-4B87-8C9A-C1700C083EE9
- rawValue : CF66A6B3-2D17-4B87-8C9A-C1700C083EE9
(lldb)
*.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment