【发布时间】:2018-03-18 22:52:29
【问题描述】:
我有一个下载的 JSON 文件。在其中,有重复的对象是两种类型中的一种 - [Double] 或 [[[Double]]]。
我正在尝试对自定义结构使用 Codable 协议来将数据转储到对象中。为了解决上述问题,我实际上将更简单的[Double] 转换为相同的[[[Double]]] 类型。
稍后,当使用这些数据时,我正在努力将其转换回一个更简单的单层数组。我希望我可以强制将其强制转换为单个 as! [Double] 类型。我还能怎么做?每个数组层都需要一个“for in”循环吗?
另外,我如何调整我的 Geometry 结构,这样我就不会为这个属性使用不同类型的数组?我想知道coordinates 属性是否可以更改为Any 类型或其他类型?
struct Geometry: Codable {
let coordinates: [[[Double]]]
let type: String
enum CodingKeys: String, CodingKey {
case coordinates
case type
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)
if type == "Point" {
let typeFromMapbox = try container.decode([Double].self, forKey: .coordinates)
coordinates = [[typeFromMapbox]]
} else { // THIS IS A POLYGON
coordinates = try container.decode([[[Double]]].self, forKey: .coordinates)
}
}
}
我只是从 Swift 开始和学习
感谢任何帮助、指示或见解
谢谢
【问题讨论】:
-
发布 JSON。这将使每个人都更容易为您提供帮助。
标签: arrays swift casting codable