I have a downloaded JSON file. Within it, there are repeating objects that are either 1 of 2 types - either a [Double]
or a [[[Double]]]
.
I am trying to use a Codable protocol for a custom struct to dump the data into objects. To get around the above, I have actually cast the simpler [Double]
into the same [[[Double]]]
type.
Later on, when using this data, I am struggling casting this back to a simpler single-tier array. I hoped I could force cast this back to the single as! [Double]
type. How else can I do this? Would I need a "for in" loop for each array tier?
Alternatively, how can I adjust my Geometry struct so I don't mess about with different types of arrays for this property? I was wondering if the coordinates
property could be changed to be of type Any
, or some other type?
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)
}
}
}
I am only starting & learning with Swift
Appreciate any help, pointers or insights
Thanks