Created
July 13, 2017 19:08
-
-
Save Ravi61/eca9a2c7972fab20b852e7aadfc8e199 to your computer and use it in GitHub Desktop.
Code to parse JSON in an enum
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
struct Spaceship: Codable { | |
var name: String | |
var model: String | |
} | |
enum SpaceshipPlanet { | |
case spaceship(Spaceship) | |
case planet(String) | |
} | |
extension SpaceshipPlanet: Decodable { | |
enum CodingKeys: String, CodingKey { | |
case spaceship | |
case planet | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
if let ship = try container.decodeIfPresent(Spaceship.self, forKey: .spaceship) { | |
self = .spaceship(ship) | |
} else { | |
self = .planet(try container.decode(String.self, forKey: .planet)) | |
} | |
} | |
} | |
//... | |
let jsonDecoder = JSONDecoder() | |
do { | |
let data = try jsonDecoder.decode([SpaceshipPlanet].self, from: jsonData!) | |
data.forEach({ print($0) }) | |
} catch { | |
print("parse error") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment