Mym*_*odo 8 error-handling swift do-catch
我想使用连续的try语句.如果有人返回错误,我想继续下一个,否则返回值.下面的代码似乎工作正常,但我最终会得到一个大的嵌套do catch金字塔.在Swift 3.0中有更聪明/更好的方法吗?
do {
return try firstThing()
} catch {
do {
return try secondThing()
} catch {
return try thirdThing()
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*n R 17
如果不需要从这些函数调用抛出的实际错误,那么您可以使用try?将结果转换为可选,并使用nil-coalescing运算符链接调用??.
例如:
if let result = (try? firstThing()) ?? (try? secondThing()) ?? (try? thirdThing()) {
return result
} else {
// everything failed ...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果在所有内容都失败的情况下抛出最后一个方法的错误,请使用try?除最后一个方法调用之外的所有方法:
return (try? firstThing()) ?? (try? secondThing()) ?? (try thirdThing())
Run Code Online (Sandbox Code Playgroud)
Nik*_*uhe 13
如果马丁的回答太简洁你的口味,你可以选择单独的挡块.
do {
return try firstThing()
} catch {}
do {
return try secondThing()
} catch {}
do {
return try thirdThing()
} catch {}
return defaultThing()
Run Code Online (Sandbox Code Playgroud)
由于每个投掷函数的结果立即返回,因此不需要嵌套.