【问题标题】:How to avoid nesting do/catch statements in Swift2如何避免在 Swift2 中嵌套 do/catch 语句
【发布时间】:2015-12-08 21:27:30
【问题描述】:

我一直想这样做:

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 块的反转?

【问题讨论】:

    标签: swift2 do-catch


    【解决方案1】:

    在 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
    }
    

    这取决于您需要哪种处理方式。

    【讨论】:

    • 我认为这也可以,但我收到了一个 xCode 错误 - 在初始化之前使用了常量“结果”
    • 那么你在catch 中有一个路径,它允许代码继续执行并到达另一行,即使result 没有被分配。但是,如果您 returnthrow 出错,您将不会收到该错误。
    • 是的,完全正确,我没有 return 或 throw 放入我的 catch 块,所以我需要它或需要将 result 设为可选。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多