Bullionist
Bullionist

Reputation: 2210

Get Value from AnyObject Response Swift

How to get the values of id,content,name from the response from the server. The response from the server is as an AnyObject and if I print, it appears like given below...

{
 content = xxxx
 id = 22
 name = yyyy
}

Thanks in advance.

Upvotes: 5

Views: 7259

Answers (1)

Frankie
Frankie

Reputation: 11928

AnyObject can be downcast into other types of classes, so many possibilities!

//if you're confident that responseObject will definitely be of this dictionary type
let name = (responseObject as! [String : AnyObject])["name"] 

//optional dictionary type
let name = (responseObject as? [String : AnyObject])?["name"] 

//or unwrapping, name will be inferred as AnyObject
if let myDictionary = responseObject as? [String : AnyObject] {
    let name = myDictionary["name"]
}

//or unwrapping, name will be inferred as String
if let myDictionary = responseObject as? [String : String] {
    let name = myDictionary["name"]
}

Check out the reference. There's even a section on AnyObject

Upvotes: 18

Related Questions