ios 在 Swift 3 中处理 try 和 throws

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39751923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:23:36  来源:igfitidea点击:

Handling try and throws in Swift 3

iosswiftswift3

提问by KexAri

Before Swift 3 I was using:

在 Swift 3 之前,我使用的是:

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

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

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

回答by Eric Aya

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

这里的区别在于Data(contentsOf: url)不再返回 Optional ,而是抛出。

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

所以你可以在 Do-Catch 中使用它,但没有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)
}

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

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

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