If-statement for when Enum doesn’t match

I have cases that I need to check if an enum does not match certain case. I have been using these:

enum Enum {
    case a, b(Int)
}
let a = Enum.a

if case .b = a {
    // nothing
} else {
    print("something")
}

switch a {
case .b: break
default: print("something")
}

They are quite clunky for what I intend to do, is there a more Swifty way to go about this?

2 Likes

Well, you could manually define a nested “case only” simple enum:

enum Foo {
  case a(Int)
  case b(String)
  
  enum Case { case a, b }
  
  var `case`: Case {
    switch(self) {
    case .a: return .a
    case .b: return .b
    }
  }
}

And then you can write:

let x = Foo.a(0)

if x.case == .a {
  // do stuff
}
1 Like

You can leave out the associated values when testing a case already; your code didn't add anything. (The OP already used the capability in his/her example.) And your code didn't solve the original problem.

This is unfortunately not a thing. I pitched a solution here, but would need someone to shepherd it: Automatically derive properties for enum cases

…what?

In my example, the nested Foo.Case enum is Equatable, as all simple enums are. Therefore, the == and != operators can be used on values of type Foo.Case.

The case property on Foo returns an instance of Foo.Case. Thus, when x is an instance of Foo, it follows that x.case is an instance of Foo.Case, and can be used with !=.

The confusion is because your example used == instead of !=. I assume that was a typo. Thus it appeared unrelated. And since if x.case == .a {} is no improvement over if case .a = x {}, the general usefulness was not immediately evident either.

Your suggestion was on‐topic and reasonable:

if x.case != .a {
    // There is no pattern equivalent for this.
}

if x.case == y.case {
    // This cannot be done just by switching either.
}
2 Likes