Created
August 9, 2019 11:27
-
-
Save Edudjr/e6d0050c3fb6e4ba2d8997a6cd3e5a0a to your computer and use it in GitHub Desktop.
Codable/Decodable example for parsing JSON with optional parameters
This file contains 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
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