快速编程 NSErrorPointer 错误等

标签 swift xcode6 nserror

var data: NSDictionary = 
    NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: error) as NSDictionary;

这行代码给我错误

NSError is not convertable to NSErrorPointer.

所以我想把代码改成:

var data: NSDictionary =
     NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary;

这会将 NSError 错误转换为 NSErrorPointer。但是后来我得到一个新错误并且无法理解它:

NSError! is not a subtype of '@|value ST4'

最佳答案

自 Swift 1 以来,这些类型和方法发生了很大变化。

  1. NS 前缀被删除
  2. 这些方法现在抛出异常而不是采用错误指针
  3. 不鼓励使用 NSDictionary。而是使用 Swift 字典

这导致以下代码:

do {
    let object = try JSONSerialization.jsonObject(
        with: responseData,
        options: .allowFragments)
    if let dictionary = object as? [String:Any] {
        // do something with the dictionary
    }
    else {
        print("Response data is not a dictionary")
    }
}
catch {
    print("Error parsing response data: \(error)")
}

的,如果你不关心具体的解析错误:

let object = try JSONSerialization.jsonObject(
    with: responseData,
    options: .allowFragments)
if let dictionary = object as? [String:Any] {
    // do something with the dictionary
}
else {
    print("Response data is not a dictionary")
}

原始答案

你的 NSError 必须被定义为一个 Optional 因为它可以是 nil:

var error: NSError?

您还需要考虑在将返回 nil 的解析或返回数组的解析中存在的错误。为此,我们可以使用带有 as? 运算符的可选转换。

这给我们留下了完整的代码:

var possibleData = NSJSONSerialization.JSONObjectWithData(
    responseData,
    options:NSJSONReadingOptions.AllowFragments,
    error: &error
    ) as? NSDictionary;

if let actualError = error {
    println("An Error Occurred: \(actualError)")
}
else if let data = possibleData {
   // do something with the returned data
}

关于快速编程 NSErrorPointer 错误等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24176383/

相关文章:

swift - 使用 SwiftUI 预览崩溃 @Binding : communication with the app was interrupted

ios - 调用之间的调度和延迟

xcode6 - 我是否需要在 iTunes Connect 中启用 "Multiplayer Compatibility"才能让 Game Center 排行榜在全局范围内运行?

parse-platform - Swift 2.0 和 Parse - 'init()' 不可用 : use 'init(domain:code:userInfo:)'

uitableview - 无法在 UITableView 编辑模式下删除按钮

ios - 我可以让 iOS Simulator 监听键盘事件以进行调试吗?

ios - 使用 cordova 3.8.0 创建的新 iOS 项目在 Resources 文件夹中缺少 de.lproj、en.lproj、localizable.strings 文件

ios - NSError 域检查条件在 iOS 8 中失败

ios - 从类型 '(_, _, _) throws -> ()' 的抛出函数到非抛出函数类型的无效转换 '(URLResponse?, Data?, Error?) -> Void

arrays - 将循环计数放在数组索引中