如何避免Swift2中嵌套do/catch语句
我一直想这样做:如何避免Swift2中嵌套do/catch语句,swift2,do-catch,Swift2,Do Catch,我一直想这样做: do { let result = try getAThing() } catch { //error } do { let anotherResult = try getAnotherThing(result) //Error - result out of scope } catch { //error } do { let result = try getAThing() do { let anot
do {
let result = try getAThing()
} catch {
//error
}
do {
let anotherResult = try getAnotherThing(result) //Error - result out of scope
} catch {
//error
}
do {
let result = try getAThing()
do {
let anotherResult = try getAnotherThing(result)
} catch {
//error
}
} catch {
//error
}
但似乎只能做到这一点:
do {
let result = try getAThing()
} catch {
//error
}
do {
let anotherResult = try getAnotherThing(result) //Error - result out of scope
} catch {
//error
}
do {
let result = try getAThing()
do {
let anotherResult = try getAnotherThing(result)
} catch {
//error
}
} catch {
//error
}
有没有一种方法可以在不必嵌套do/catch块的情况下将不可变的
结果
保留在作用域中?是否有一种防止错误的方法类似于我们使用guard
语句作为if/else块的逆语句?在Swift 1.2中,您可以将常量的声明与常量的赋值分开。(请参阅中的“常数现在更强大、更一致”)因此,结合Swift 2错误处理,您可以:
let result: ThingType
do {
result = try getAThing()
} catch {
// error handling, e.g. return or throw
}
do {
let anotherResult = try getAnotherThing(result)
} catch {
// different error handling
}
或者,有时我们并不真正需要两个不同的do
-catch
语句,一个catch
语句将在一个块中处理两个潜在抛出的错误:
do {
let result = try getAThing()
let anotherResult = try getAnotherThing(result)
} catch {
// common error handling here
}
这取决于你需要什么样的处理方式 我想这也行,但我得到了一个xCode错误-初始化之前使用的常量“result”
catch
中有一个路径,允许代码继续执行并到达另一行,即使未指定result
。但是如果您返回
或抛出
错误,您将不会得到该错误。是的,这完全正确,我没有返回或抛出我的catch块,因此我需要返回或抛出,或者需要使结果可选。