ios - [NSDictionary]!?不能转换为 [NSDictionary]?

标签 ios swift xcode6

我得到了

'[NSDictionary]!? is not convertible to [NSDictionary]?' error on following code.

  var jsonResult:[NSDictionary]! = [NSJSONSerialization.JSONObjectWithData(urlData, options:NSJSONReadingOptions.MutableContainers, error: &error1)] as? [NSDictionary]!

为什么会发生这种情况?

最佳答案

首先:删除NSJSONSerialization.JSONObjectWithData周围的[],如果把它放在数组中会变得非常困难转换它。

使用以下内容

var jsonResult = NSJSONSerialization.JSONObjectWithData(urlData, options:NSJSONReadingOptions.MutableContainers, error: &error1) as! NSDictionary

as? 可选择强制转换为给定类型。因此,您最终会得到 [NSDictionary]! -> [NSDictionary]!? 类型的可选类型,它实际上无法转换为 [NSDictionary]! 但无法包装。这对于选择性强制转换和展开是没有意义的,只需首先使用展开强制转换即可。

apple docs在这种有关可选的情况下真的很有帮助!

对我的第一点进行更多解释:您将 NSJSONSerialization.JSONObjectWithData 的返回值放入数组中,这将导致 [AnyObject?] 无法真正转换为 [AnythingElse ] 因为你必须在转换之前解开选项。我不知道有任何内置的方法可以做到这一点。并且在您的场景中没有任何意义。在所有转换之后,您仍然可以将值包装在一个数组中,您可以通过

var jsonResult = [NSJSONSerialization.JSONObjectWithData(urlData, options:NSJSONReadingOptions.MutableContainers, error: &error1) as! NSDictionary]

关于ios - [NSDictionary]!?不能转换为 [NSDictionary]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32529724/

相关文章:

ios - 即使应用程序未在后台运行,如何使 iOS 应用程序执行一些代码?

ios - 与不这样做相比,为 UITableView 调用 beginUpdates/endUpdates 有什么好处?

jquery fancybox弹出窗口显示在屏幕中间

ios - 单击 UIButton Swift 更改 View Controller (无 Storyboard )

ios - 连接到具有身份验证的站点时,Swift 3 NSURLSession/NSURLConnection HTTP 加载失败

ios8 - 无法在 iPhone 上运行示例 heathkit 项目 FitStoreandRetrieveHealthKitData

iphone - OpenGL ES 2.0 如何正确设置 glVertexAttribPointers

ios - 如何创建在触发功能时通过的测试?

ios - Swift - 分段控制 - 切换多个 View

ios - Xcode 6 和 iOS 静态框架