Fast errors dropped from here are not processed

I had code working in Xcode 6, but since I got Xcode 7, I cannot figure out how to fix it. There is an error in the let jsonresult line which says that the Error thrown from here is not processed. Code below:

func connectionDidFinishLoading(connection: NSURLConnection!) {

    let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

    print(jsonresult)

    let number:Int = jsonresult["count"] as! Int

    print(number)

    numberElements = number

    let results: NSDictionary = jsonresult["results"] as! NSDictionary

    let collection1: NSArray = results["collection1"] as! NSArray

thank

+4
source share
1 answer

If you look at the definition of a method JSONObjectWithDatain swift 2, it throws an error.

class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject

In swift 2, if any function throws an error, you need to handle it with a do-try-catch block

Here is how it works

func connectionDidFinishLoading(connection: NSURLConnection!) {
    do {
        let jsonresult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        print(jsonresult)

        let number:Int = jsonresult["count"] as! Int

        print(number)

        numberElements = number

        let results: NSDictionary = jsonresult["results"] as! NSDictionary

        let collection1: NSArray = results["collection1"] as! NSArray
    } catch {
        // handle error
    }
}

Or, if you do not want a descriptor error, you can force it to use a keyword try!.

let jsonresult:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        print(jsonresult)

! . , .

+17

All Articles