【发布时间】:2018-01-22 04:16:57
【问题描述】:
我想使用连续的 try 语句。如果一个返回错误,我想继续下一个,否则返回值。 下面的代码似乎工作正常,但我最终会得到一个大的嵌套 do catch 金字塔。在 Swift 3.0 中有更聪明/更好的方法吗?
do {
return try firstThing()
} catch {
do {
return try secondThing()
} catch {
return try thirdThing()
}
}
【问题讨论】:
-
在
do中执行所有try语句,并在catch中捕获任何异常。根本不需要嵌套它们。 -
如果 OP 只想在 firstThing 失败时运行第二件事并在 secondThing 失败时运行thirdThing,这将不起作用@Pancho。
-
感谢@Pancho,但由于我要返回值(或错误),任何代码都不会执行第一次返回。
-
@Abizern 这是真的。在这种情况下,必须用 if-else 或 switch 语句替换 do-catch,这不会减少代码或使其更漂亮。
-
为什么投反对票?
标签: swift error-handling do-catch