-2

From the book IOS 8 SDK Development 2nd Edition by Chris Adamson on the end of Chapter 6.

I have an issue with the error call and how exactly I convert it from the old swift to the new swift, with do.. and try here's my block of code

func handleTwitterData (data: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) {
    if let dataValue = data {
        var parseError : NSError? = nil
        let jsonObject : AnyObject? =  NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions(0), error: &parseError)
        print("JSON error: \(parseError)\nJSON response: \(jsonObject)")
} else {
    print("handleTwitterData received no data")
    }
}

1 Answers1

0

In swift 2.0 you will not use error parameter.

If objective-c function has last parameter as NSError**, swift 2.0 remove it and mark it as a function that can throw exception.

So you do not need to write that parameter, but need to use swift exceptions syntax instead.

do {
    let jsonObject : AnyObject? = try NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions(0))
} catch {
    print("\(error)")
}
Vasyl Khmil
  • 2,548
  • 1
  • 20
  • 36
  • Swift errors are not exceptions. This question already has many good answers anyway. – Eric Aya Jan 14 '16 at 14:13
  • @EricD. where I wrote that swift errors are exceptions? – Vasyl Khmil Jan 14 '16 at 14:15
  • In your answer, twice: `function that can throw exception` and `but need to use swift exceptions syntax instead` – Eric Aya Jan 14 '16 at 14:16
  • @EricD. First of all I just copy pasted code from question to show how should it be changed to work correctly. And I don't see where in my answer say that swift errors are exceptions. I can also copy some random line and say here it is. – Vasyl Khmil Jan 14 '16 at 14:19
  • @EricD. Also I haven't define dataValue variable, so it will not compile. Did you saw that? – Vasyl Khmil Jan 14 '16 at 14:20
  • Look at [this](https://www.evernote.com/l/AOy9GlslrdlBAbu47j3jpFiTcMkm9nk5ztE). I didn't invent anything. *You* wrote this, which is wrong, and that's what I was saying in my first comment. – Eric Aya Jan 14 '16 at 14:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100676/discussion-between-vasyl-khmil-and-eric-d). – Vasyl Khmil Jan 14 '16 at 14:26