基于错误的枚举关联值,使用多个 catch 和条件进行快速错误处理

akr*_*akr 2 error-handling enums swift

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

例子:

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")
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 5

是的当然!

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

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

}
catch {
    print("all other errors")
}
Run Code Online (Sandbox Code Playgroud)