在 Swift 3 中处理 try 和 throws [英] Handling try and throws in Swift 3

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

问题描述

在使用 Swift 3 之前:

Before Swift 3 I was using:

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

但是我现在必须使用dotrycatch.我不熟悉这种语法.我将如何复制这种行为?

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

推荐答案

这里的区别在于 Data(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)
}

请注意,您仍然可以将 guardtry? 一起使用,而不是 try,但可能会忽略可能的错误消息.在这种情况下,您不需要 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 中处理 try 和 throws的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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