Gintas_ Gintas_ - 2 months ago 29
Swift Question

How to read Double from AnyObject in Swift 3?

I had it working on previous Swift versions like this:

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


As I understand, there is no
doubleValue
anymore, so I replaced it like this:

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")


And it crashes:

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

Answer

You just need to cast it from Any to [String: Any] or to another type you need to get from it:

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