Swift catch enum case with binding

Viewed 683

If I have a custom error

enum MyError: Error {
  case error1
  case error2
}

I can catch all errors of that type and bind a variable:

do {
} catch let e as MyError {
} catch {
  // everything else
}

or I can catch a specific error without binding a variable

do {
} catch MyError.error1 {
} catch {
  // everything else, including MyError.error2
}

but how do I catch a specific error and bind a variable?

2 Answers

If I understand you correctly, you want a variable inside a catch to be the specific error case of a specific type of error.

If so, you can do this:

do {
    try something()
} catch let err1 as MyError where err1 == .error1 {
    print(err1)
} catch {
    print(error)
}

I think what you need is the following:

    do {
        throw(MyError.error2)
    } catch let error as MyError {
        switch error {
        case .error1:
            print("error 1 happened")
            return
        case .error2:
            print("error 2 happened")
            return
        }
    } catch let error {
        print(error)
        return
    }
Related