Enums in Swift

Enums in Swift

"Enums" define a finite state of any entity. This entity could be a direction in a compass, name of planets, day's in a weekend, brands of vehicles and so on so forth.


This behavior of defining a finite state is extended to the programming world of software languages in a more readable and understandable format for developers. ex: Swift

In Swift the basic syntax would be as follows

enum <name> {
    case <case>
}

To express a enum of Days in  a week we can write the code as shown below.

Here <name> is name of the enum , DaysInWeek and I have give a Type to It, which is  Integer.



enum DaysInAWeek:Int {
    case Sunday = 0
    case Monday,Tuesday,Wednesday,Thursday,Friday
    case Saturday
    
}


To initialize a var with enum value Monday , it can be written as follows.


let monday = DaysInAWeek.Monday



Another way to initialize it is as follows.

let monday = DaysInAWeek(rawValue: 1)


If the rawValue passed does not match with any of the enumeration case it would return a nil. Meaning in the above case if we pass any value greater than 6, the value returned by the enum will be nil.


Note: In Swift case values of a enumeration(i.e Sunday,Monday..) are actual values. This means we don't have to give them explicit( Assigning value with "=" operator) or implied value(by giving a type as Int).

Having said that, what would the above defined DaysInWeek enum look like. This is useful when we know there is no meaningful raw-value for a enum case.


enum DaysInAWeek {
    case Sunday
    case Monday,Tuesday,Wednesday,Thursday,Friday
    case Saturday
    
}



Enums like a simple swift class can have properties and method too, as explained below. I have added one computed property of dayMessageText , which simply returns a "Weekend day off Sunday".
We can also have a function to work as per the requirement, printMyDayMessage prints the text that we pass as well as the enum case.



enum DaysInAWeek:Int {
    case Sunday
    case Monday,Tuesday,Wednesday,Thursday,Friday
    case Saturday
    
    var dayMessageText: String {
        get {
            var message:String
            switch self {
            case .Sunday:
                message = "Weekend day off Sunday "
            default:
                message = ""
            }
            return message
        }
    }
    
    func printMyDayMessage(message:String) -> String {
        return "\(self) = \(message)"
    }
}

Comments