已为Swift 5.1更新
假定以下抛出函数:
enum ThrowableError: Error { case badError(howBad: Int)}func doSomething(everythingIsFine: Bool = false) throws -> String { if everythingIsFine { return "Everything is ok" } else { throw ThrowableError.badError(howBad: 4) }}尝试
当您尝试调用可能抛出的函数时,有2个选项。
您可以通过将呼叫围绕在do-catch块中来承担 处理错误 的责任:
do { let result = try doSomething()}catch ThrowableError.badError(let howBad) { // Here you know about the error // Feel free to handle or to re-throw // 1. Handle print("Bad Error (How Bad Level: (howBad)") // 2. Re-throw throw ThrowableError.badError(howBad: howBad)}或者只是尝试调用该函数,然后 将错误传递 给调用链中的下一个调用者:
func doSomeOtherThing() **_throws_** -> Void { // Not within a do-catch block. // Any errors will be re-thrown to callers. let result = try doSomething()}尝试!
当您尝试访问其中包含nil的隐式展开的可选内容时会发生什么?是的,的确如此,该应用程序将崩溃!尝试也一样!它基本上会忽略错误链,并声明“行将成灾”的情况。如果被调用的函数没有引发任何错误,则一切正常。但是,如果失败并抛出错误,则
您的应用程序将完全崩溃 。
let result = try! doSomething() // if an error was thrown, CRASH!
尝试?
Xpre 7 beta 6中引入了一个新关键字。它 返回一个可选的 关键字,该关键字解开成功的值,并通过返回nil捕获错误。
if let result = try? doSomething() { // doSomething succeeded, and result is unwrapped.} else { // Ouch, doSomething() threw an error.}或者我们可以使用警卫:
guard let result = try? doSomething() else { // Ouch, doSomething() threw an error.}// doSomething succeeded, and result is unwrapped.最后一点,通过使用
try?注释,您将丢弃发生的错误,因为该错误已转换为nil。使用尝试?当您更多地关注成功和失败时,而不是失败的原因上。
使用合并运算符
您可以使用合并运算符?? 尝试一下?在出现故障时提供默认值:
let result = (try? doSomething()) ?? "Default Value"print(result) // Default Value



