基于错误的枚举关联值的具有多个catch和条件的Swift错误处理

时间:2019-05-13 13:18:57

标签: swift error-handling enums

有没有一种方法可以基于错误枚举的关联值来捕获某些条件下的错误?

示例:

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")
}

1 个答案:

答案 0 :(得分:2)

当然可以!

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

do {
    try f()
}
catch Errors.error1(let str) where str != nil{

}
catch {
    print("all other errors")
}