我有这行代码,我想提取“标题”键:
var title = jParams["title"] as! String
但它不会让我编译,如果我收到红色的错误消息:
Cannot subscript a value of a type AnyObject with an index of type String
当用println(jParams)在日志中显示jParams的内容时,我得到以下内容:
INCOMING LIST ParaMETERS (jParameters) Optional({ title = "Example List"; values = ( { id = 1; name = "Line 1"; },{ id = 2; name = "Line 2"; },{ id = 3; name = "Line 3"; } ); })
我是Swift的新手,所以我不熟悉处理JSON来处理这些类型问题的细节.可能有什么不对?
//jParams comes from a JSON server response var data = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil,error: nil) if data != nil { var jdata = JSON(data: data!) var jParams=jdata["responseData"]["exTradata"]["params"]
解决方法
在您的编辑中,它看起来像您正在使用SwiftyJSON.
如果确实如此,您可以使用SwiftyJSON的dictionaryValue属性帮助编译器知道字典中的内容:
let jParams = jdata["responseData"]["exTradata"]["params"].dictionaryValue
然后,您应该能够访问您的值而无需向下转换:
let title = jParams["title"]
因为SwiftyJSON会推断出值的正确类型.