6
votes

I have this code

let path : String = "http://apple.com"
let lookupURL : NSURL = NSURL(string:path)!
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(lookupURL, completionHandler: {(data, reponse, error) in

  let jsonResults : AnyObject

  do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
  } catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
  }

 // do something

})

task.resume()

but it is failing on the let task line with the error:

invalid conversion from throwing function of type (__.__.__) throws to non throwing function type (NSData?, NSURLResponse?, NSError?) -> Void

what is wrong? This is Xcode 7 beta 4, iOS 9 and Swift 2.


edit:

the problem appears to be with these lines

  do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
  } catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
  }

I remove these lines and the let task error vanishes.

4

4 Answers

9
votes

Looks like the issue is in the catch statement. The following code won't produce the error you've described.

do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
} catch {
    // failure
    print("Fetch failed: \((error as NSError).localizedDescription)")
}

I do realize that the code you've provided is supposed to be correct, so you should consider filing a bug with Apple about this.

2
votes

Apple replaced NSError with ErrorType in Swift 2 Edit: in many libraries.

So replace your own explicit usage of NSError with ErrorType.

Edit

Apple has done this for several libraries in Swift 2, but not all yet. So you still have to think where to use NSError and where to use ErrorType.

2
votes

You can also assume no errors with:

let jsonResults = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) 

Look, Ma... no hands!

0
votes

For swift 3 :

 do {
    jsonResults = try JSONSerialization.JSONObject(with: data!, options: [])
// success ...
 } catch {// failure
    print("Fetch failed: \((error as NSError).localizedDescription)")
}