1

我使用了 Web 服务并将 JSON 数据保存到我的 jsonArray 中。现在我正在尝试将数据应用到 CLLocationCoordinate2D 中,如下所示:

CLLocationCoordinate2D(latitude: self.jsonArray["JSONResults"][0]["lat"],longitude: self.jsonArray["JSONResults"][0]["long"])

Swift 编译器告诉我:

Cannot invoke initializer for type 'CLLocationCoordinate2D' with an argument list of type (latitude: JSON, longitude: JSON)

我尝试使用 as Int 但它仍然不起作用。我怎样才能正确地正确转换它?

我的 JSON 数据示例:

{
"long" : "121.513358",
"tel" : "(02)2331-6960",
"lat" : "25.044976",
"add" : "xxx",
"region" : "yyy",
"name" : "zzz"
}
4

1 回答 1

1

看起来您正在使用库 SwiftyJSON 来解码您的 JSON。

这个库创建类型的对象JSON,你必须在使用它之前提取它们的值。

由于您在响应中的值似乎是Strings 并且您需要Doubles CLLocationCoordinate2D,这应该有效:

let lat = self.jsonArray["JSONResults"][0]["lat"].stringValue
let long = self.jsonArray["JSONResults"][0]["long"].stringValue
CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!)

在此示例中,我使用 SwiftyJSON 非可选 getters stringValue.string但是,如果值可以为 nil,您也可以使用可选的 getter :

if let lat = self.jsonArray["JSONResults"][0]["lat"].string, let long = self.jsonArray["JSONResults"][0]["long"].string, let latitude = Double(lat), let longitude = Double(long) {
    CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
于 2015-09-29T15:33:13.820 回答