【问题标题】:Swift error handling with multiple catch and conditions based on the error's enum associated value基于错误的枚举关联值,使用多个捕获和条件进行 Swift 错误处理
【发布时间】:2019-09-30 11:12:22
【问题描述】:

有没有办法根据错误枚举的关联值的值来捕获具有某种条件的错误?

例子:

enum Errors : Error {
    case error1(str: String?) // optional associated value
    case error2
    case error3
}

func f() throws {
    throw Errors.error1(str: nil)
}


do {
    try f()
}
catch Errors.error1(let str) {
    if(str != nil) {
        print(str!)
    }
    else {
        //throw the same error to be caught in the last catch
    }
}
catch {
    print("all other errors")
}

【问题讨论】:

    标签: swift error-handling enums


    【解决方案1】:

    当然可以!

    catch 中,您可以对错误进行模式匹配,就像在 switch 语句中一样。您可以在“使用 Do-Catch 处理错误”部分下的 Swift guide 中阅读有关此内容的更多信息。这意味着你可以使用where:

    do {
        try f()
    }
    catch Errors.error1(let str) where str != nil{
    
    }
    catch {
        print("all other errors")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      相关资源
      最近更新 更多