How to use Any in Codable Type

后端 未结 11 727
猫巷女王i
猫巷女王i 2020-11-29 04:20

I\'m currently working with Codable types in my project and facing an issue.

struct Person: Codable
{
    var id: Any
}

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 05:24

    There is a corner case which is not covered by Luca Angeletti's solution.

    For instance, if Cordinate's type is Double or [Double], Angeletti's solution will cause an error: "Expected to decode Double but found an array instead"

    In this case, you have to use nested enum instead in Cordinate.

    enum Cordinate: Decodable {
        case double(Double), array([Cordinate])
    
        init(from decoder: Decoder) throws {
            if let double = try? decoder.singleValueContainer().decode(Double.self) {
                self = .double(double)
                return
            }
    
            if let array = try? decoder.singleValueContainer().decode([Cordinate].self) {
                self = .array(array)
                return
            }
    
            throw CordinateError.missingValue
        }
    
        enum CordinateError: Error {
            case missingValue
        }
    }
    
    struct Geometry : Decodable {
        let date : String?
        let type : String?
        let coordinates : [Cordinate]?
    
        enum CodingKeys: String, CodingKey {
    
            case date = "date"
            case type = "type"
            case coordinates = "coordinates"
        }
    
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            date = try values.decodeIfPresent(String.self, forKey: .date)
            type = try values.decodeIfPresent(String.self, forKey: .type)
            coordinates = try values.decodeIfPresent([Cordinate].self, forKey: .coordinates)
        }
    }
    

提交回复
热议问题