我有一个国家和坐标的大型JSON数组。示例元素如下所示:
[" CountryName":" El Salvador"," CapitalName":" SanSalvador"," CapitalLatitude": " 13.7"" CapitalLongitude":" -89.200000"" COUNTRYCODE":" SV"&# 34; ContinentName":"中美洲"],[" CountryName":"赤道几内亚"," CapitalName":&#34 ;马拉博"" CapitalLatitude":" 3.75"" CapitalLongitude":" 8.783333"" COUNTRYCODE&# 34;:" GQ"" ContinentName":"非洲"]
然后我有一个for循环,它应该从数组中的数据创建注释。
for location in locations {
let annotation = MGLPointAnnotation()
annotation.title = location["CountryName"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: location["CapitalLatitude"] as! Double, longitude: location["CapitalLongitude"] as! Double)
mapView.addAnnotation(annotation)
}
但是除非我能从纬度和经度上剥去引号,否则这不会起作用。我试过这样做:
location["CapitalLatitude"] = Double(location[CapitalLatitude])
location["CapitalLongitude"] = Double(location[CapitalLongitude])
但是由于尝试连接不相关的类型值而导致错误。
错误是展开可选项后的值为nil。我知道我没有正确提供纬度/长数。
如何摆脱纬度/长数周围的引号?手动做太多了。
答案 0 :(得分:2)
您正尝试使用以下类型访问location
:
location["CapitalLatitude"] = Double(location["CapitalLatitude"])
location["CapitalLongitude"] = Double(location["CapitalLongitude"])
试试。
答案 1 :(得分:2)
问题是您的数据存储是愚蠢的。将它转换为你真正想要的东西,比如结构:
struct Country {
let name : String
let capitalName : String
let capitalLatitude : Double
let capitalLongitude : Double
let code : String
let continent : String
}
转换只是一行代码:
let arr = [["CountryName":"El Salvador","CapitalName":"SanSalvador","CapitalLatitude":"13.7","CapitalLongitude":"-89.200000","CountryCode":"SV","ContinentName":"Central America"],["CountryName":"Equatorial Guinea","CapitalName":"Malabo","CapitalLatitude":"3.75","CapitalLongitude":"8.783333","CountryCode":"GQ","ContinentName":"Africa"]]
let arr2 = arr.map {
Country(name: $0["CountryName"]!,
capitalName: $0["CapitalName"]!,
capitalLatitude: Double($0["CapitalLatitude"]!)!,
capitalLongitude: Double($0["CapitalLongitude"]!)!,
code: $0["CountryCode"]!,
continent: $0["ContinentName"]!
)
}
和宾果,你有一系列的国家,现在使用它很方便。