我需要创建一个结构如下的对象
distances.append([
"distanceInMiles":String(distanceInMiles),
"distanceInMeters":String(distanceInMeters),
"places": [
{
"name":nameI,
"city":cityI,
"lat":latitudeI,
"lon":longitudeI,
"coordinate":coordinateI
}, {
"name":nameJ,
"city":cityJ,
"lat":latitudeJ,
"lon":longitudeJ,
"coordinate":coordinateJ
}
]
])
我的变量声明应该是什么?
我尝试过
var distances = [ Dictionary<String,String>()]
我知道了
参数标签'(_ :, _ :)'与任何可用的重载都不匹配
如何进一步调试呢?
答案 0 :(得分:1)
只需为这种复杂的结构编写一个struct / class:
struct Distance { // You might want to find a better name
let distanceInMiles: Double
let distanceInMeters: Double
let places: [Place]
}
struct Place {
let name: String
let city: String
let lat: Double
let long: Double
let coordinate: CLLocationCoordinate2D // You might want to make this a computed property instead
}
然后您可以创建一个Distance
数组:
var distances = [Distance]()
distance.append(Distance(
distanceInMiles: distanceInMiles,
distanceInMeters: distanceInMeters,
places: [
Place(name: nameI, city: cityI, lat: latitudeI, long: longitudeI, coordinate: coordinateI),
Place(name: nameJ, city: cityJ, lat: latitudeJ, long: longitudeJ, coordinate: coordinateJ),
]
))
如您所见,美观与类似JSON的结构非常相似。
顺便说一句,如果您打算将此结构转换为JSON并将其发送到某个地方,则可以使两个结构都符合Codable
。