试试!&尝试?有什么区别,什么时候使用? [英] try, try! & try? what’s the difference, and when to use each?

查看:22
本文介绍了试试!&尝试?有什么区别,什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 2.0 中,Apple 引入了一种处理错误的新方法(do-try-抓住).几天前,在 Beta 6 中引入了一个更新的关键字(try?).另外,我知道我可以使用 try!.3 个关键字之间有什么区别,何时使用?

In Swift 2.0, Apple introduced a new way to handle errors (do-try-catch). And few days ago in Beta 6 an even newer keyword was introduced (try?). Also, knew that I can use try!. What's the difference between the 3 keywords, and when to use each?

推荐答案

已针对 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 个选择.

try

You have 2 options when you try calling a function that may throw.

您可以通过在 do-catch 块中包围您的调用来负责处理错误:

You can take responsibility of handling errors by surrounding your call within a do-catch block:

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)
}

或者只是尝试调用函数,然后将错误传递给调用链中的下一个调用者:

Or just try calling the function, and pass the error along to the next caller in the call chain:

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!

试试?

Xcode 7 beta 6 中引入的一个新关键字.它返回一个可选,用于解开成功的值,并通过返回 nil 来捕获错误.

try?

A new keyword that was introduced in Xcode 7 beta 6. It returns an optional that unwraps successful values, and catches error by returning nil.

if let result = try? doSomething() {
    // doSomething succeeded, and result is unwrapped.
} else {
    // Ouch, doSomething() threw an error.
}

或者我们可以使用守卫:

Or we can use guard:

guard let result = try? doSomething() else {
    // Ouch, doSomething() threw an error.
}
// doSomething succeeded, and result is unwrapped.

最后一点,通过使用 try? 请注意,您正在丢弃发生的错误,因为它已转换为 nil.用试试?当你更多地关注成功和失败,而不是事情失败的原因时.

One final note here, by using try? note that you’re discarding the error that took place, as it’s translated to a nil. Use try? when you’re focusing more on successes and failure, not on why things failed.

您可以使用合并运算符 ??尝试?提供默认值以防万一:

You can use the coalescing operator ?? with try? to provide a default value incase of failure:

let result = (try? doSomething()) ?? "Default Value"
print(result) // Default Value

这篇关于试试!&尝试?有什么区别,什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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