Compiler error when comparing enumerated values ββwith associated values?
class MyClass
{
enum MyEnum {
case FirstCase
case SecondCase(Int)
case ThirdCase
}
var state:MyEnum!
func myMethod ()
{
if state! == MyEnum.FirstCase {
// Do something
}
}
}
I am getting a compiler error pointing to operator if
::
Binary operator '==' cannot be applied to two "MyClass.MyEnum" Operands
If I use the operator instead switch
, 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 statement switch
looks too verbose: I just want do something
for .FirstCase
, and nothing else. The operator if
makes more sense.
What happens to the enums and ==
?
EDIT: This is ultra weird. After defining the version switch
and navigating to other (completely unbound) parts of my code and returning, the if
-statement version (a force-compatible unbound property in the case of a fixed enum) compiles without error. I can only conclude that it has something to do with some corrupted cache in the parser that cleared up along the way.
EDIT 2 (Thanks to @LeoDabus and @MartinR): It seems that the error appears when I set the bound value to a different enum case (not the one I am comparing to - in this case, .SecondCase). I still don't understand why this is causing this compiler error, in particular ("Cannot use binary operator" == "..."), or what it means.
source to share
As you said in a comment, your enum type is actually bound by values. In this case, there is no ==
default operator for the enumeration type .
But you can use pattern matching even in the statement if
(since Swift 2):
class MyClass {
enum MyEnum {
case FirstCase
case SecondCase
case ThirdCase(Int)
}
var state:MyEnum!
func myMethod () {
if case .FirstCase? = state {
}
}
}
Here .FirstCase?
is a shortcut for .Some(MyEnum.FirstCase)
.
In your switch statement, it is state
not automatically expanded, even if it is not necessarily expanded implicitly (otherwise you might not match nil
). But the same pattern can be used here:
switch state {
case .FirstCase?:
// do something...
default:
break
}
source to share
class MyClass {
enum MyEnum {
case FirstCase
case SecondCase
case ThirdCase
}
var state: MyEnum!
func myMethod() {
guard
let state = state else { return }
if state == MyEnum.FirstCase {
// Do something
print(true)
} else {
print(false)
}
}
}
let myClass = MyClass()
myClass.state = .FirstCase
myClass.myMethod()
myClass.state = .SecondCase
myClass.myMethod()
source to share