私は現在Codable
、自分のプロジェクトで型を扱っており、問題に直面しています。
struct Person: Codable
{
var id: Any
}
id
上記のコードでは、String
またはのいずれかになりますInt
。id
これがタイプの理由ですAny
。
私はそうでAny
はないことを知っていCodable
ます。
私が知る必要があるのは、どうすればそれを機能させることができるかということです。
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)
}
}