Skip to content

Instantly share code, notes, and snippets.

@Ravi61
Created July 13, 2017 19:08
Show Gist options
  • Save Ravi61/eca9a2c7972fab20b852e7aadfc8e199 to your computer and use it in GitHub Desktop.
Save Ravi61/eca9a2c7972fab20b852e7aadfc8e199 to your computer and use it in GitHub Desktop.
Code to parse JSON in an enum
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