2016-10-14 56 views
-2

我目前正在做一个谷歌地图自动完成功能的ios swift应用程序。在SWIFT 2.0我不喜欢这样获得的经度和纬度值:Swift 3 downcasting JSON Dictionary

let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary 
let lat = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as! Double 
let lon = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as! Double 

但随着SWIFT 3,它不工作了。我能做什么?

回答

1
  • 首先,使用NSDictionary,使用所有的斯威夫特本地Dictionary
  • 二不使用valueForKey,使用键订阅
  • 所有的三不使用mutableContainers在Swift,如果你想改变某些东西,请使用varDictionary

为了方便起见声明JSON词典的一个类型别名

typealias JSONDictionary = [String:Any] 

在夫特3的编译器需要知道的各类所有中间对象的,最安全的解决方案是

if let dic = try JSONSerialization.jsonObject(with:data!, options: []) as? JSONDictionary { 
    if let results = dic["results"] as? JSONDictionary, 
    let geometry = results["geometry"] as? JSONDictionary, 
    let location = geometry["location"] as? JSONDictionary, 
    let latitudes = location["lat"] as? [Double], !latitudes.isEmpty, 
    let longitudes = location["lng"] as? [Double], !longitudes.isEmpty { 
     let lat = latitudes[0] 
     let lng = longitudes[0] 
    } 
} 

对于那种嵌套的JSON,考虑使用像SwiftyJSON这样的库。

+0

非常感谢它的工作正常! –