Owen26 Owen26 - 1 month ago 9
Swift Question

Xcode Swift - Any not convertible to NSDictionary

let orderID = (responceDictionary as NSDictionary).value(forKeyPath: "result.id") as? String


Error:
'[AnyHashable : Any]?' is not convertible to 'NSDictionary'

I'm not entirely sure how to cast from Any -> NSDictionary but as a String, it seems to throw errors with what I try.

let orderID = (responceDictionary as! NSDictionary).value(forKeyPath: "result.id") as? String


The above compiles but using this throws another error: Will always fail.

Moltin.sharedInstance().cart.order(withParameters: orderParameters, success: { (responceDictionary) in

let orderID = (responceDictionary as NSDictionary).value(forKeyPath: "result.id") as? String

Answer Source

[any hashable:any] is not a NSDictionary. In the second varriation you gurantee it will be castable, but it wont and thus crash.

Ignore NSDictionary. Know it feels hard when comming from Obj-C. Personal I used recently this:

let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary<String, Any>
let conversationID = jsonDictionary["conversationId"] as! String?

conversationID will be an optional String. Casting into a object or struct if you use it a lot. Saves the hassle of casting each time