Skip to content

Instantly share code, notes, and snippets.

@Kdan
Last active April 11, 2018 16:44
Show Gist options
  • Select an option

  • Save Kdan/c78822cb337e86aa7ca9a27248f3e85f to your computer and use it in GitHub Desktop.

Select an option

Save Kdan/c78822cb337e86aa7ca9a27248f3e85f to your computer and use it in GitHub Desktop.
enum PersonCodingKeys: String, CodingKey {
case name
case pets
}
// CHALLENGE 1: Nested Heterogeneous Array Decoded.
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PersonCodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// Get the container containing the whole list of pets.
var petsContainer = try self.nestedUnkeyedContainer(forKey: key)
// Initialise empty list of pets.
var pets = [Pet]()
var tmpContainer = petsContainer
// For each pet...
while !container.isAtEnd {
// Get the container containing the type of the pet.
let typeContainer = try petsContainer.nestedContainer(keyedBy: Discriminator.self)
// Decode the PetFamily type from the type container.
let family: PetFamily = try typeContainer.decode(PetFamily.self, forKey: PetFamily.discriminator)
// Decode the correctly mapped type according to the family.
if let type = family.getType() as? Pet.Type {
pets.append(try tmpContainer.decode(type))
}
}
self.pets = pets
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment