-1

I've been having a problem understanding what xcode wants from me when it gives me the "Extra argument 'error' in call" it keeps pointing to

if let feed = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as? NSDictionary,

I read somewhere that in swift 2 I should add do { but everytime I add it I just keep breaking more stuff. What's the correct syntax in swift 2?

This is the code:

override func viewDidLoad() {
    super.viewDidLoad()
    let request = NSURLRequest(URL: NSURL(string: feedURL)!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
        if let feed = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as? NSDictionary,
            title = feed.valueForKeyPath("feed.entry.im:name.label") as? String,
            artist = feed.valueForKeyPath("feed.entry.im:artist.label") as? String,
            imageURLs = feed.valueForKeyPath("feed.entry.im:image") as? [NSDictionary] {
                if let imageURL = imageURLs.last,
                    imageURLString = imageURL.valueForKeyPath("label") as? String {
                        self.loadImageFromURL(NSURL(string:imageURLString)!)
                }
            self.titleLabel.text = title
            self.titleLabel.hidden = false
            self.artistLabel.text = artist
            self.artistLabel.hidden = false

        }
    }
}
Mohammed
  • 15
  • 1
  • 3

2 Answers2

2

Here is the new way of error handling in swift 2...

do {
     if let feed = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSDictionary {
      // Success block...
   }
} catch {
    print(error)
}
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
  • Oh yeah I've seen that before but how can replace it with the old way of error handling without breaking everything around it? or should i just rewrite the whole thing? – Mohammed Nov 02 '15 at 04:44
  • just copy your code from title to `self.artistLabel.hidden = false` and put it in to success block in above condition thats it... – Bhavin Bhadani Nov 02 '15 at 04:46
0

The way to do this in Swift 2 is

let feed = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
pbush25
  • 5,228
  • 2
  • 26
  • 35
  • I've tried removing it once before but I got a "Call can throw, but it is not marked with 'try' and the error is not handled" thanks for your help – Mohammed Nov 02 '15 at 04:41
  • The compiler will accept the above code and not complain about it. If you do it as above without the `if` this will work fine. – pbush25 Nov 02 '15 at 04:46
  • @pbush25 - Nowadays, if you don't want to use `try` - `catch` syntax, you'd use `try?` or `try!`. Simply doing `if let ...` is not sufficient. – Rob May 25 '16 at 22:55