0

I have an error and I need to check if it's NOT a specific case of MyError:

enum MyError {
    case one(description: String)
    case two(description: String)
    case three(description: String)
    (...)
}

I can easily check if an error variable is a specific case of MyError:

if case MyError.one = error {
    // this is definitely error MyError.one
}

How can I make sure it's NOT a specific case?

if (...) { // something like: !(case MyError.one = error)
    // this is any other case but NOT MyError.one
}

I know I can do this with the guard keyword or if-else but I'm wondering if there is a more elegant solution (as guard needs a return):

guard case MyError.one = error else {
    // this is any other case but NOT MyError.one
    return
}
Andriy Gordiychuk
  • 6,163
  • 1
  • 24
  • 59
pawello2222
  • 46,897
  • 22
  • 145
  • 209

1 Answers1

0

You can also add helper methods to your enum:

enum MyError {
    case one(description: String)
    case two(description: String)
    case three(description: String)

    var isOne:Bool {
        if case MyError.one = self {
            return true
        }
        return false
    }
}

Unfortunately, doing anything simpler than this is not currently possible. Here are a couple of good threads on this and related subjects:

  1. How to compare enum with associated values by ignoring its associated value in Swift?
  2. How to test equality of Swift enums with associated values
Andriy Gordiychuk
  • 6,163
  • 1
  • 24
  • 59
  • Yes, I could do do the same with an `if-else` statement. I'm just trying to find a way to do it like `if !(case MyError.one = error) { ...` – pawello2222 May 07 '20 at 22:29
  • Thanks, it does not exactly solve my problem but I see it can't be done as I hoped. The solution with a computed property should be sufficient (although it's not ideal). – pawello2222 May 07 '20 at 23:28