// 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>'
什么是正确的方式让这个工作?
使用感叹号来解开可选项:
原文链接:https://www.f2er.com/swift/318843.htmlvar 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 } }