Last active
April 10, 2018 18:27
-
-
Save Kdan/134492218ddc6deb7cc0f18c73ee69b1 to your computer and use it in GitHub Desktop.
This file contains 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
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