【问题标题】:Swift 3 downcasting JSON DictionarySwift 3 向下转换 JSON 字典
【发布时间】:2016-10-14 13:26:54
【问题描述】:

我目前正在做一个带有谷歌地图自动完成功能的 ios swift 应用程序。在 swift 2.0 中,我确实喜欢这样来获取经度和纬度值:

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,它不再工作了。我能做什么?

【问题讨论】:

    标签: json dictionary swift3


    【解决方案1】:
    • 首先,不要使用NSDictionary,使用Swift原生Dictionary
    • 其次不要使用valueForKey,使用密钥订阅
    • 第三个不要在 Swift 中使用 mutableContainers,如果您想更改某些内容,请使用 var Dictionary

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

    typealias JSONDictionary = [String:Any]
    

    在 Swift 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 之类的库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 2018-03-30
      • 2017-03-05
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      相关资源
      最近更新 更多