从 AnyObject 响应中获取值 Swift

5
如何从服务器响应中获取id、content和name的值。 服务器响应是一个AnyObject类型的对象,如果我打印它,它会显示如下...
{
 content = xxxx
 id = 22
 name = yyyy
}

提前致谢。

1个回答

18

AnyObject 可以向下转换为其他类型的类,因此有许多可能性!

//if you're confident that responseObject will definitely be of this dictionary type
let name = (responseObject as! [String : AnyObject])["name"] 

//optional dictionary type
let name = (responseObject as? [String : AnyObject])?["name"] 

//or unwrapping, name will be inferred as AnyObject
if let myDictionary = responseObject as? [String : AnyObject] {
    let name = myDictionary["name"]
}

//or unwrapping, name will be inferred as String
if let myDictionary = responseObject as? [String : String] {
    let name = myDictionary["name"]
}

查看参考资料。甚至有关于AnyObject的部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接