【发布时间】:2015-05-01 02:25:29
【问题描述】:
我使用的是最新版本的 Xcode,但出现以下错误:“Cast from 'NSData?'到不相关的类型 'NSDictionary' 总是失败"
使用此代码:
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.dataWithJSONObject(dataObject!, options: nil, error: nil) as! NSDictionary
编程语言:Swift
更新代码:
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary
}
- 现在在我运行我的应用程序时获取断点。
对不起,我还是堆栈溢出的新手
【问题讨论】:
-
是的,它是 NSDictionary
-
let weatherDictionary : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataObject, options: NSJSONReadingOptions.MutableContainers, error: nil)使用此代码并检查weatherDictionary是NSArray或NSDictionary。 -
仍然出现错误
-
请返回并编辑您的原始问题。在底部添加一个“##Edit”块。发布您的新代码和您收到的确切错误消息,并告诉我们哪一行引发了错误。
-
@Python_is_cool - 两点:首先,如果您遇到问题,请不要将
nil用于error参数。这是一种让解析器解释失败原因的机制。有错误很疯狂,但不想看到错误是什么。其次,您应该将NSData转换为字符串并直观地检查它(也许编辑向我们展示它的样子的问题)。例如,println(NSString(data: dataObject, encoding: NSUTF8StringEncoding))。当我们查看实际的响应字符串时,问题可能会变得不言而喻。