Parth Adroja Parth Adroja - 1 month ago 8
iOS Question

How can I access some object from `Any` Type?

In Swift 2.2, I used to write like this

let dict = [String: AnyObject]()
let value = dict.objectForKey("price") as! Double
print(value)


But as
AnyObject
is now replaced with type
Any
how can I access dictionary values as no method for
objectForKey
for type Any.
Do i need to type cast to
AnyObject
?

Answer

First of all you can't use objectForKey for swift native type. you can simply use subscript as i mentioned in comments and also use if let for safely unwrap.

 let dict: [String: Any] = ["price": 2.0 ]
 if let value = dict["price"] as? Double {
  print(value)
}

Note: As always, do not use NSMutableDictionary in Swift. this type lack type information

Comments