Skip to content

Instantly share code, notes, and snippets.

@Kdan
Last active April 10, 2018 18:27
Show Gist options
  • Save Kdan/134492218ddc6deb7cc0f18c73ee69b1 to your computer and use it in GitHub Desktop.
Save Kdan/134492218ddc6deb7cc0f18c73ee69b1 to your computer and use it in GitHub Desktop.
class ClassWrapper<T: ClassFamily, U: Decodable>: Decodable {
/// The family enum containing the class information.
let family: T
// The decoded object. Can be any subclass of U.
let object: U?
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Discriminator.self)
// Decode the family with the discriminator.
family = try container.decode(T.self, forKey: T.discriminator)
// Decode the object by initialising the corresponding type.
if let type = family.getType() as? U.Type {
object = try type.init(from: decoder)
} else {
object = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment