Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw value for enum case must be a literal

Tags:

ios

swift

I have this enum:

enum GestureDirection:UInt {     case Up =       1 << 0     case Down =     1 << 1     case Left =     1 << 2     case Right =    1 << 3 } 

But on every case I get error:

Raw value for enum case must be a literal

I dont get it.

Swift 1.2, Xcode 6.3.2

like image 773
Arbitur Avatar asked May 19 '15 12:05

Arbitur


People also ask

What is raw value in enum?

Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case).

What is the advantage of using raw values in enum?

Raw values gives us the possibility to specify some behavior for every single case in the enumeration. First, we specify that in Directions every raw value is going to hold a String. After that, we store those messages directly into the Enum.


1 Answers

That's because 1 << 0 isn't a literal. You can use a binary literal which is a literal and is allowed there:

enum GestureDirection:UInt {     case Up =       0b000     case Down =     0b001     case Left =     0b010     case Right =    0b100 } 

Enums only support raw-value-literals which are either numeric-literal (numbers) string-literal­ (strings) or boolean-literal­ (bool) per the language grammar.

Instead as a workaround and still give a good indication of what you're doing.

like image 195
Benjamin Gruenbaum Avatar answered Oct 14 '22 04:10

Benjamin Gruenbaum