Swift 2 iOS 9 Do Catch Try crashing with unexpected nil found

◇◆丶佛笑我妖孽 提交于 2019-11-26 18:27:21

问题


I'm trying to become familiar with the new do catch statements with swift 2 and iOS 9

My problem is that when an error occurs with NSURLSession, the data parameter returns nil, and error returns something. In iOS 8 this was expected functionality and we simply used if statements to find out whether or not Data was nil

However with do catch, there is the new try keyword which I thought was meant to see if something works, if it doesn't then default to whatever code is written in catch

However, because data is nil I am getting an unexpected crash. Is this expected functionality, why isn't catch being called when my try method fails?

I'm using NSURLSession to pull data from an API.

I create a dataTaskWith request like this:

 let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        print(request)
        print(response)
        print(error)

        do {

            let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

Crashes right here because data! is nil.. because there was an NSURLSession error

            print(jsonResult)




        } catch {
            print(error)
        }

    })
    task.resume()

回答1:


This is because catch only catches what a functions "throws".

NSJSONSerialization throws, but force unwrapping an empty Optional doesn't, it always crashes.

Use if let or the new guard function to safely unwrap your values.

do {
    if let myData = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? NSDictionary {
        print(jsonResult)
    }
} catch {
    print(error)
}


来源:https://stackoverflow.com/questions/32187683/swift-2-ios-9-do-catch-try-crashing-with-unexpected-nil-found

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