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?
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc.
toList(). contains(""); (Suppose your enum is called E.) Here inside "" you should put a name of an enum constant for which you wish to check if it is defined in the enum or not.
1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.
You can use the if-case
operand
if case .foo = test { doSomething() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With