【问题标题】:Swift Errors Thrown from here are not handled不处理从这里抛出的 Swift 错误
【发布时间】:2015-08-29 07:00:54
【问题描述】:

我的代码在 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

谢谢

【问题讨论】:

    标签: json swift error-handling xcode7


    【解决方案1】:

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

    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)
    

    与其他以 !这是一个危险的操作。如果出现错误,您的程序将崩溃。

    【讨论】:

    • 谢谢。这是一个很好的答案。我确实知道 do {}catch{},但我没有将其余代码放在 NSJSONSerialization 行中。谢谢:)
    猜你喜欢
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多