Using raw values in swift enumeration

Using raw values with swift enumeration :

In swift, we can assign raw values while defining an enumeration.Means these are default values for enumeration cases. Let’s take a look at the below example :

enum Day : Int{
    case sunday = 1
    case monday = 2
    case tuesday = 3
    case wednesday = 4
    case thrusday = 5
    case friday = 6
    case saturday = 7
}

Here, we have assigned integer raw values to each case. One thing we should keep in mind that each raw values must be unique.It can be string,character, integer or floating point number. We can print these values like below :

Day.sunday.rawValue

We can initialize a variable with raw value like this :

let today = Day(rawValue : 7)

But remember that if the rawValue is not available in the definition, it will return nil.
We can use optional binding like below to handle this :

enum Day : Int{
    case sunday = 1
    case monday = 2
    case tuesday = 3
    case wednesday = 4
    case thrusday = 5
    case friday = 6
    case saturday = 7
}

let value = 7

if let today = Day(rawValue : value){
    switch today{
    case .sunday :
        print ("Today is Sunday")
    default :
        print ("Today is not Sunday")
    }
}else{
    print ("Invalid input")
}

Implicitly assigning raw values :

Beauty of swift : if you assign value only to the first case , it will automatically assign values to all others . Check below :

enum Day : Int{
    case sunday = 1,monday,tuesday,thrusday,friday,saturday
}

It will assign value 2 to monday, 3 to tuesday etc.What about the below program :

enum Day : String{
    case sunday,monday,tuesday,thrusday,friday,saturday
}

It will assign the string representation of each name , e.g. for tuesday, its rawValue will be “tuesday”.

Difference between raw and associate values :

The main difference between raw and associate values is that raw values are set while defining the enumeration time , but associate values are set while creating one variable of the enumeration type. Also, raw values are constant but associate values are set while creating a variable.

Leave a Reply