Swift 2 iOS 9赶上尝试崩溃,发现意外的零 [英] Swift 2 iOS 9 Do Catch Try crashing with unexpected nil found

查看:109
本文介绍了Swift 2 iOS 9赶上尝试崩溃,发现意外的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过swift 2和iOS 9熟悉新的do catch语句

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

我的问题是,当NSURLSession发生错误时,data参数返回nil,而错误返回某些信息.在iOS 8中,这是预期的功能,我们只使用了if语句来查明数据是否为空

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

但是对于do catch,有一个新的try关键字,我认为该关键字旨在查看是否可以正常工作,如果它不能默认为catch中编写的任何代码

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

但是,由于数据为零,所以我遇到了意外崩溃.这是预期的功能吗,为什么当我的try方法失败时为什么不调用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?

我正在使用NSURLSession从API中提取数据.

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

我创建像这样的dataTaskWith请求:

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

在这里因为数据而崩溃!为零..,因为出现了NSURLSession错误

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

            print(jsonResult)




        } catch {
            print(error)
        }

    })
    task.resume()

推荐答案

这是因为catch仅捕获函数抛出"的内容.

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

NSJSONSerialization抛出,但是强制展开一个空的Optional却没有,它总是崩溃.

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

使用if let或新的guard函数安全地解包您的值.

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

这篇关于Swift 2 iOS 9赶上尝试崩溃,发现意外的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆