class MyClass
{
enum MyEnum {
case FirstCase
case SecondCase(Int)
case ThirdCase
}
var state:MyEnum!
func myMethod ()
{
if state! == MyEnum.FirstCase {
// Do something
}
}
}
I get the compiler error pointing at the if
statement::
Binary operator '==' cannot be applied to two 'MyClass.MyEnum' operands
If instead, I use a switch
statement, there is no problem:
switch state! {
// Also, why do I need `!` if state is already an
// implicitly unwrapped optional? Is it because optionals also
// are internally enums, and the compiler gets confused?
case .FirstCase:
// do something...
default:
// (do nothing)
break
}
However, the switch
statement feels too verbose: I just want to do something
for .FirstCase
, and nothing otherwise. An if
statement makes more sense.
What's going on with enums and ==
?
EDIT: This is ultra-weird. After settling for the switch
version and moving on to other (totally unrelated) parts of my code, and coming back, the if
-statement version (comnparing force-unwrapped property against fixed enum case) is compiling with no errors.
I can only conclude that it has something to do with some corrupted cache in the parser that got cleared along the way.
EDIT 2 (Thanks @LeoDabus and @MartinR): It seems that the error appears when I set an associated value to the other enum case (not the one I am comparing against - in this case, .SecondCase). I still don't understand why that triggers this compiler error in particular ("Can't use binary operator '=='..."), or what that means.