我一直想这样做:
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 1.2 Blog Entry中的“常量现在更强大且更一致”.)因此,将其与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 }
这取决于您需要什么类型的处理.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。