如何避免在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 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
}

这取决于您需要什么类型的处理.

猜你在找的Swift相关文章