快速编程NSErrorPointer错误等 [英] swift programming NSErrorPointer error etc

查看:261
本文介绍了快速编程NSErrorPointer错误等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这行代码给我错误

NSError is not convertable to NSErrorPointer.

所以我随后考虑将代码更改为:

So I then thought to change the code to:

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

,它将把NSError错误变成NSErrorPointer.但是然后我得到了一个新错误,无法理解:

which would turn the NSError error into a NSErrorPointer. But then I get a new error and cannot make sense of it:

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

推荐答案

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

These types and methods have changed a lot since Swift 1.

  1. NS前缀已删除
  2. 这些方法现在抛出异常,而不是使用错误指针
  3. 不建议使用NSDictionary.而是使用Swift字典
  1. The NS prefix is dropped
  2. The methods now throw exceptions instead of taking an error pointer
  3. Use of NSDictionary is discouraged. Instead use a Swift dictionary

这将导致以下代码:

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)")
}

其中,如果您不关心特定的解析错误:

Of, if you don't care about the specific parsing 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:

Your NSError has to be defined as an Optional because it can be nil:

var error: NSError?

您还想考虑解析中将返回nil的错误或解析中返回的数组的错误.为此,我们可以在as?运算符中使用可选的强制转换.

You also want to account for there being an error in the parsing which will return nil or the parsing returning an array. To do that, we can use an optional casting with the as? operator.

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

That leaves us with the complete code:

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错误等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆