Swift Errors Thrown from here are not handled

早过忘川 提交于 2019-12-22 07:24:22

问题


I have had my code working in Xcode 6 but since I got Xcode 7 I cannot figure out how to fix this. The let jsonresult line has an error that says Error thrown from here are not handled. Code is 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

Thanks


回答1:


If you look at the definition of JSONObjectWithData method in swift 2 it throws error.

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

In swift 2 if some function throws an error you have to handle it with 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 don't want handle error you can force it with try! keyword.

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

As with other keywords that ends ! this is a risky operation. If there is an error your program will crash.



来源:https://stackoverflow.com/questions/30817107/swift-errors-thrown-from-here-are-not-handled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!