decodeable if nil code example
Example: decodeable if nil
struct Result: Decodable {
let animal: Animal?
enum CodingKeys : CodingKey {
case animal
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let string = try container.decode(String.self, forKey: .animal)
// here I made use of the fact that an invalid raw value will cause the init to return nil
animal = Animal.init(rawValue: string)
}
}