Swift - Auto-Increment for Enumeration Raw Values

Introduction

You can use integer values instead of strings as enumeration raw type.

The following code are representing the day of a week:

enum DayOfWeek: Int {
   case Monday = 1
   case Tuesday = 2
     case Wednesday = 3
     case Thursday = 4
     case Friday = 5
     case Saturday = 6
     case Sunday = 7
}

Here, each day of the week is assigned an integer value-Monday is assigned 1, Tuesday is assigned 2, and so on.

The following statements show how it can be used:

var d = DayOfWeek.Wednesday
print(d.rawValue)   //prints out 3

When integer values are used for raw values within an enumeration, they are automatically incremented if no values are specified for subsequent members.

For example, the following code snippet shows that only the first member within the DayOfWeek enumeration is set to a value:

enum DayOfWeek: Int {
   case Monday = 1
   case Tuesday
   case Wednesday
   case Thursday
   case Friday
   case Saturday
   case Sunday
}

Due to auto-incrementing of integer raw values, the following will still work:

var d = DayOfWeek.Thursday
print(d.rawValue)   //prints out 4

Related Topic