32

Consider:

enum Test {
    case foo
    case bar
    case baz
    case etc
}

var test: Test = ...

I would like to test whether the enum is bar in particular. I could just use a switch statement:

switch test {
case .bar:
    doSomething()
default:
    break
}

It would be far neater if I could instead use if:

if test == .bar {
    doSomething()
}

But unless I'm missing something, there is no way to do that:

Binary operator '==' cannot be applied to two 'Test' operands

Is this possible, and if not, was this a deliberate language design decision?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
user280993
  • 461
  • 1
  • 5
  • 5
  • 1
    Your code compiles fine as `Test` doesn't have any associated values (Swift only synthesises `Hashable` conformance for enums without associated values). Please show us your real code. – Hamish Feb 12 '17 at 00:00
  • Assuming `Test` in your real code does in fact have associated values – possible duplicate of [How to compare enum with associated values by ignoring its associated value in Swift?](http://stackoverflow.com/q/31548855/2976878). Also see [How to test equality of Swift enums with associated values](http://stackoverflow.com/q/24339807/2976878) – Hamish Feb 12 '17 at 00:01
  • @Hamish: Sorry, yes, I can confirm that my real code has associated values for some cases. However, I'm trying to compare against one that doesn't. Assume that `baz` and `etc` have associated values, but `foo` and `bar` do not. – user280993 Feb 12 '17 at 00:33
  • In that case – possible duplicate of [How to test equality of Swift enums with associated values](http://stackoverflow.com/q/24339807/2976878) :) – Hamish Feb 12 '17 at 00:35

1 Answers1

60

You can use the if-case operand

if case .foo  = test {
   doSomething()
}
Stefan
  • 2,098
  • 2
  • 18
  • 29