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

前端之家收集整理的这篇文章主要介绍了swift – ‘(String,AnyObject)’不能转换为'[String:AnyObject]’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. // response is of type AnyObject!
  2. let responseDic = response as [String : AnyObject]
  3. let userDic = responseDic["user"] as [String : AnyObject]

但是,在最后一行,我得到错误

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

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

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

但我得到:

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

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

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

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

  1. if let user: AnyObject = responseDic["user"] {
  2. if let userDic = user as? [String : AnyObject]{
  3. //do stuff with userDic
  4. }
  5. }

猜你在找的Swift相关文章