📜  如果 nil 可解码 - 任何代码示例

📅  最后修改于: 2022-03-11 14:59:54.544000             🧑  作者: Mango

代码示例1
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)
    }
}