我有一个由国家和坐标组成的大型JSON数组。示例元素如下所示:
[“countryname”:“萨尔瓦多”,“capitalname”:“萨尔瓦多”,“capitaltitude”:“13.7”,“capitallongitude”:“-89.200000”,“countrycode”:“sv”,“continentname”:“中美洲”],[“countryname”:“赤道几内亚”,“capitalname”:“马拉博”,“capitaltitude”:“3.75”,“capitallongitude”:“8.783333”,“countrycode”:“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])

但由于试图连接不相关的类型值,这给了我一个错误。
错误是,展开可选项后,值为零。我知道我没有正确提供lat/long数字。
如何去掉lat/long数字周围的引号?手工操作的数量太多了。

最佳答案

您正在尝试使用以下类型访问location

location["CapitalLatitude"] = Double(location["CapitalLatitude"])
location["CapitalLongitude"] = Double(location["CapitalLongitude"])

试试看。

关于arrays - 在Swift中,如何将数组中的数字字符串转换为 double 数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45685808/

10-12 00:19
查看更多