Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I test whether an enum value is a particular case without using a switch statement? [duplicate]

Tags:

enums

swift

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?

like image 405
user280993 Avatar asked Feb 11 '17 23:02

user280993


People also ask

Can enums be used in switch statements?

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.

How do you know if an enum is present?

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.

Can enum be used in switch case in C?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.


1 Answers

You can use the if-case operand

if case .foo  = test {    doSomething() } 
like image 82
Stefan Avatar answered Sep 19 '22 21:09

Stefan