Reputation: 32091
// response is of type AnyObject!
let responseDic = response as [String : AnyObject]
let userDic = responseDic["user"] as [String : AnyObject]
However, on the last line, I get the error:
'(String, AnyObject)' is not convertible to '[String : AnyObject]'
So I'm guessing looking up a key in a dictionary returns an optional value, so then I tried:
let userDic = responseDic["user"]? as [String : AnyObject]
But I get:
'String' is not convertible to 'DictionaryIndex<String, AnyObject>'
What's the proper way to get this to work?
Upvotes: 11
Views: 20001
Reputation: 64684
Use an exclamation point instead to unwrap the optional:
var response: AnyObject! = ["user" : [String : AnyObject]()]
let responseDic = response as [String : AnyObject]
let userDic: [String : AnyObject] = responseDic["user"]! as [String : AnyObject]
And if you want to make sure there is a non-nil value for the key 'user' and it is a [String : AnyObject] you can use an if let:
if let user: AnyObject = responseDic["user"] {
if let userDic = user as? [String : AnyObject]{
//do stuff with userDic
}
}
Upvotes: 13