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

问题描述

在中,苹果推出了一种处理错误的新方法(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?

推荐答案

假设以下抛出函数: / p>

Assume the following throwing function:

enum ThrowableError : ErrorType { case BadError }

func doSomething() throws -> String {
    if everythingIsFine {
        return "Everything is ok"
    } else {
        throw ThrowableError.BadError
    }
}



尝试



当您尝试调用一个函数时,您有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 {
    // Here you know about the error
    // Feel free to handle to re-throw
}

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

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



try!



当您尝试访问隐藏的包装可选内容时,会发生什么情况?是的,真的,应用程序将崩溃!
同样的尝试!它基本上忽略了错误链,并声明了做或死的情况。如果被调用函数没有发生任何错误,一切顺利。但是如果失败并且发生错误,您的应用程序将简单地崩溃

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

或者我们可以使用新的awesome guard关键字:

Or we can use new awesome guard keyword:

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

这里最后一个注意事项是使用尝试?请注意,您正在丢弃所发生的错误,因为它被翻译为零。
使用try?当你专注于成功和失败,而不是为什么事情失败。

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.

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

09-06 02:39