Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value from AnyObject Response Swift

Tags:

ios

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.

like image 514
Shaik MD Ashiq Avatar asked May 06 '15 00:05

Shaik MD Ashiq


1 Answers

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

like image 128
Frankie Avatar answered Oct 11 '22 10:10

Frankie