Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'(String, AnyObject)' is not convertible to '[String : AnyObject]'

Tags:

swift

// 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?

like image 750
Snowman Avatar asked Jul 27 '14 15:07

Snowman


1 Answers

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
    }
}
like image 53
Connor Avatar answered Nov 16 '22 00:11

Connor