Answers for "decodeable if nil"

0

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)
    }
}
Posted by: Guest on June-07-2020

Browse Popular Code Answers by Language