swift programming NSErrorPointer error etc

user3732493 picture user3732493 · Jun 12, 2014 · Viewed 34.5k times · Source
var data: NSDictionary = 
    NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: error) as NSDictionary;

This line of code gives me error

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;

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'

Answer

drewag picture drewag · Jun 12, 2014

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

  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

This results in the following code:

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

Original Answer

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

var error: NSError?

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
}