5

我的代码在 Xcode 6 中工作,但自从我得到 Xcode 7 后,我无法弄清楚如何解决这个问题。let jsonresult 行有一个错误,指出从这里抛出的错误未处理。代码如下:

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

谢谢

4

1 回答 1

21

如果您查看JSONObjectWithDataswift 2 中的方法定义,它会引发错误。

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

在 swift 2 中,如果某些函数抛出错误,您必须使用 do-try-catch 块处理它

下面是它的工作原理

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
    }
}

或者,如果您不想处理错误,您可以使用try!关键字强制它。

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

与结束的其他关键字一样!这是一个危险的操作。如果出现错误,您的程序将崩溃。

于 2015-06-13T10:42:05.487 回答