试试! & 尝试?有什么区别,什么时候使用?

2024-03-30

In 斯威夫特2.0 http://ahmedabdurrahman.com/2015/08/22/swift-2-0/,Apple引入了一种新的错误处理方式(do-try-catch)。 几天前,Beta 6 中引入了一个更新的关键字(try?)。 另外,知道我可以使用try!。 这 3 个关键字之间有什么区别,以及何时使用每个关键字?


更新为 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)
  }
}

try

当您尝试调用可能抛出异常的函数时,您有两个选择。

你可以承担责任处理错误通过将您的调用包含在 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()
}

try!

当您尝试访问其中包含 nil 的隐式解包选项时会发生什么?是的,没错,应用程序会崩溃! 尝试也一样!它基本上忽略了错误链,并声明“要么做,要么死”的情况。如果被调用的函数没有抛出任何错误,则一切正常。但如果失败并抛出错误,你的应用程序将会崩溃.

let result = try! doSomething() // if an error was thrown, CRASH!

try?

Xcode 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

试试! & 尝试?有什么区别,什么时候使用? 的相关文章

随机推荐