'(String,AnyObject)'不能转换为'[String:AnyObject]'

时间:2014-07-27 15:33:54

标签: swift

// response is of type AnyObject!
let responseDic = response as [String : AnyObject]
let userDic = responseDic["user"] as [String : AnyObject]

然而,在最后一行,我收到错误:

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

所以我猜测在字典中查找一个键会返回一个可选值,所以我试过了:

let userDic = responseDic["user"]? as [String : AnyObject]

但我明白了:

'String' is not convertible to 'DictionaryIndex<String, AnyObject>'

让这个工作的正确方法是什么?

1 个答案:

答案 0 :(得分:13)

请使用感叹号来打开可选项:

var response: AnyObject! = ["user" : [String : AnyObject]()]
let responseDic = response as [String : AnyObject]
let userDic: [String : AnyObject] = responseDic["user"]! as [String : AnyObject]

如果你想确保密钥'user'有一个非零值,它是[String:AnyObject]你可以使用if let:

if let user: AnyObject = responseDic["user"] {
    if let userDic = user as? [String : AnyObject]{
        //do stuff with userDic
    }
}