Skip to content

Instantly share code, notes, and snippets.

@Edudjr
Created August 9, 2019 11:27
Show Gist options
  • Save Edudjr/e6d0050c3fb6e4ba2d8997a6cd3e5a0a to your computer and use it in GitHub Desktop.
Save Edudjr/e6d0050c3fb6e4ba2d8997a6cd3e5a0a to your computer and use it in GitHub Desktop.
Codable/Decodable example for parsing JSON with optional parameters
class Drink: Codable {
var name: String
var color: String?
private enum CodingKeys: String, CodingKey {
case name, color
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
color = try? values.decode(String.self, forKey: .color)
}
}
let json = """
{"name":"caipirinha", "color":"green"}
""".data(using: .utf8)!
let json2 = """
{"name":"gin tonica"}
""".data(using: .utf8)!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment