Last active
December 22, 2019 04:40
-
-
Save hlung/25981fcd5ed6366a1d68624490f61211 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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