swift – ‘(String,AnyObject)’不能转换为'[String:AnyObject]’

前端之家收集整理的这篇文章主要介绍了swift – ‘(String,AnyObject)’不能转换为'[String:AnyObject]’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 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>'

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

使用感叹号来解开可选项:
var response: AnyObject! = ["user" : [String : AnyObject]()]
let responseDic = response as [String : AnyObject]
let userDic: [String : AnyObject] = responseDic["user"]! as [String : AnyObject]

如果你想确定key’user’是一个非零值,它是一个[String:AnyObject],你可以使用一个if:

if let user: AnyObject = responseDic["user"] {
    if let userDic = user as? [String : AnyObject]{
        //do stuff with userDic
    }
}
原文链接:https://www.f2er.com/swift/318843.html

猜你在找的Swift相关文章