如何避免嵌套做Swift2
问题描述:
/catch语句
我一直想做到这一点:如何避免嵌套做Swift2
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
}
有没有办法让一个不变的result
范围内无需嵌套do/catch块?有没有办法来防止类似于我们如何使用guard
语句作为if/else块的反转的错误?
答
在Swift 1.2中,可以将常量的声明与常量的赋值分开。 (请参阅“现在常量是更强大和一致”的Swift 1.2 Blog Entry)。所以,结合与雨燕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错误 - 在初始化之前使用的常量'结果' – nwales
然后,您有一个'catch'路径,它允许代码继续执行并且到达另一行尽管'结果'没有被分配。但是,如果你“返回”或“抛出”一个错误,你将不会得到那个错误。 – Rob
是的,这是完全正确的,我没有返回或抛出我的catch块,所以无论我需要或需要使结果可选。 – nwales