如何从Swift 3中的AnyObject读取Double?

时间:2016-09-29 15:50:35

标签: swift swift3

我曾在以前的Swift版本上工作过:

let dictionary = responseObject as! NSDictionary
let result = dictionary.objectForKey("result")!
let geometry = result.objectForKey("geometry")!
let location = geometry.objectForKey("location")!            
let lat: Double = location.objectForKey("lat")!.doubleValue

据我所知,不再有doubleValue,所以我将其替换为:

let dictionary = responseObject as! NSDictionary
let result: AnyObject = dictionary.object(forKey: "result") as AnyObject!
let geometry: AnyObject = result.object(forKey: "geometry") as AnyObject!
let location: AnyObject = geometry.object(forKey: "location") as AnyObject!
let lat: Double = location.double(forKey: "lat")

它崩溃了:

-[__NSCFDictionary doubleForKey:]: unrecognized selector sent to instance 0x1584aba10
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary doubleForKey:]: unrecognized selector sent to instance 0x1584aba10'

1 个答案:

答案 0 :(得分:1)

您只需将其从Any转换为[String: Any]或转换为您需要的其他类型:

let dictionary = responseObject as? [String: Any] ?? [:]
let result = dictionary["result"] as? [String: Any] ?? [:]
let location = result["location"] as? [String: Any] ?? [:]
let lat = location["lat"] as? Double ?? 0