Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active December 22, 2019 04:40
Show Gist options
  • Save hlung/25981fcd5ed6366a1d68624490f61211 to your computer and use it in GitHub Desktop.
Save hlung/25981fcd5ed6366a1d68624490f61211 to your computer and use it in GitHub Desktop.
struct AnimalContainer: Decodable {
let animal: Animal
enum AnimalType: String, Decodable {
case cat
case dog
}
enum CodingKeys: String, CodingKey {
case type
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let animalType = try container.decode(AnimalType.self, forKey: .type)
switch animalType {
case .cat:
self.animal = try Cat(from: decoder)
case .dog:
self.animal = try Dog(from: decoder)
}
}
}
// Usage example
let animals = try JSONDecoder()
.decode([AnimalContainer].self, from: exampleData)
.map { $0.animal }
print(animals) // [Cat name: Kitty, Dog name: Doggy]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment