是否有可能结合渔获量?

时间:2016-10-19 15:27:57

标签: swift error-handling try-catch

我试图这样做:

 catch LocksmithError.Duplicate, LocksmithError.Allocate {...}

但我在,说错误:

  

预期' {'在' catch'图案

这是否意味着您无法合并case expression2, expression3 :等案例?这样做的原因是什么?

3 个答案:

答案 0 :(得分:4)

不,目前无法在catch子句中组合多个模式 - 语法(as detailed by the Swift Language Guide)仅允许单个模式匹配:

  

catch-clause→ catch 模式 opt where-clause opt code-block

对于已经提出的解决方案的另一种可能的解决方案,只要你的错误枚举是微不足道的(LocksmithError似乎是),就是在绑定模式之后使用where子句:

catch let error as LocksmithError where error == .Duplicate || error == .Allocate {
    // ...
}

答案 1 :(得分:2)

假设您让LocksmithError有一些rawvalue类型(例如Int),您可以在单个catch语句中绑定抛出的错误并使用其rawValue测试是否包含在几个错误情况之一中(绑定后使用where子句)。 E.g:

enum FooError: Int, Error {
    case err1 = 1, err2, err3, err4, err5
}

func foo(_ bar: Int) throws {
    if let err = FooError(rawValue: bar) { throw err }
}

func tryFoo(_ bar: Int) {
    do {
        try foo(bar)
    } catch let err as FooError where (1...4).contains(err.rawValue) {
        print("Any of 1st through 4th error!")
    } catch FooError.err5 {
        print("5th error!")
    } catch {}
}

tryFoo(1) // Any of 1st through 4th error!
tryFoo(4) // Any of 1st through 4th error!
tryFoo(5) // 5th error!

根据@ user28434的建议(谢谢!),实际上不需要应用rawValue约束,因为可以使用上面相同的方法直接查看绑定的err是否是给定案例的数组。

enum FooError: Error {
    case err1, err2, err3
}

func foo(_ bar: Int) throws {
    guard bar != 1 else { throw FooError.err1 }
    guard bar != 2 else { throw FooError.err2 }
    guard bar != 3 else { throw FooError.err3 }
}

func tryFoo(_ bar: Int) {
    do {
        try foo(bar)
    } catch let err as FooError where [.err1, .err2].contains(err) {
        print("1st or 2nd error!")
    } catch FooError.err3 {
        print("3rd error!")
    } catch {}
}

tryFoo(1) // 1st or 2nd error!
tryFoo(2) // 1st or 2nd error!
tryFoo(3) // 3rd error!

这基本上只是the accepted answer的变体(可能对catch块有用,仅涵盖两种情况,但在这种情况下,可能错误enum应该考虑重构)

答案 2 :(得分:1)

这只是一个语法问题,可以在Swift 4 +中得到改进。

现在你可以使用它:

SystemNavigation default allMethodsSelect: [:m | true]
相关问题