Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to combine catches?

I'm trying to do this:

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

But I get an error at , saying :

Expected '{' after 'catch' pattern

Does this mean you can't combine cases like case expression2, expression3 :? Any reason it's made this way?

like image 791
mfaani Avatar asked Sep 01 '25 22:09

mfaani


1 Answers

No, it's currently not possible to combine multiple patterns in a catch clause – the grammar (as detailed by the Swift Language Guide) only allows for a single pattern to match against:

catch-clause → catch pattern­opt ­where-clause­opt ­code-block­

Another possible solution to the ones proposed already, as long as your error enum is trivial (which LocksmithError appears to be), is to use a where clause after a binding pattern:

catch let error as LocksmithError where error == .Duplicate || error == .Allocate {
    // ...
}
like image 92
Hamish Avatar answered Sep 03 '25 15:09

Hamish