在Swift 3中处理尝试和抛出 [英] Handling try and throws in Swift 3

查看:83
本文介绍了在Swift 3中处理尝试和抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Swift 3之前:

Before Swift 3 I was using:

guard let data = Data(contentsOf: url) else {
                print("There was an error!)
                return
            }

但是我现在必须使用执行尝试 catch 。我我不熟悉这种语法。我如何复制这种行为?

However I now have to use do, try and catch. I'm not familiar with this syntax. How would I replicate this behaviour?

推荐答案

这里的区别在于数据(contentsOf:url)不再返回Optional,它会抛出。

The difference here is that Data(contentsOf: url) does not return an Optional anymore, it throws.

所以你可以在Do-Catch中使用它但是没有 guard

So you can use it in Do-Catch but without guard:

do {
    let data = try Data(contentsOf: url)
    // do something with data
    // if the call fails, the catch block is executed
} catch {
    print(error.localizedDescription)
}

请注意,您仍然可以使用 guard 试试?而不是试试但随后会忽略可能的错误消息。在这种情况下,您不需要Do-Catch块:

Note that you could still use guard with try? instead of try but then the possible error message is ignored. In this case, you don't need a Do-Catch block:

guard let data = try? Data(contentsOf: url) else {
    print("There was an error!")
    // return or break
}
// do something with data

这篇关于在Swift 3中处理尝试和抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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