44

私は現在Codable、自分のプロジェクトで型を扱っており、問題に直面しています。

struct Person: Codable
{
    var id: Any
}

id上記のコードでは、StringまたはのいずれかになりますIntidこれがタイプの理由ですAny

私はそうでAnyはないことを知っていCodableます。

私が知る必要があるのは、どうすればそれを機能させることができるかということです。

4

11 に答える 11

0

Luca Angeletti のソリューションでカバーされていないコーナー ケースがあります。

たとえば、Cordinate の型が Double または [Double] の場合、Angeletti のソリューションは次のエラーを引き起こします。

この場合、Cordinate では代わりにネストされた enum を使用する必要があります。

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)
    }
}
于 2018-04-23T18:48:08.880 に答える