SWIFT ENUMERATIONS

lyvennitha sasikumar
2 min readApr 5, 2021

Most developers still don’t have clarification with enumerations. Many iOS beginners confuse enum with switch statement. An enumeration is a group of common values and flexible to work with those values in a safe way within code.

Enumeration:

Enumerations are similar to structure of C. As it is
1. Enumerations can be used within a class or it can be declared outside of the class globally and values are accessed via instance of those enumerations.
2. It can be extended by ensuring standard protocol functionality.

Syntax:

enum EnumerationName: <Type>(Optional){
//enum values
}

USAGE:

Here, We define enumeration for week days:

Example:

enum Days: String{
case Sun = “Sunday”
case Mon = “Monday”
case Tue = “Tuesday”
case Wed = “Wednesday”
case Thur = “Thursday”
case Fri = “Friday”
case Sat = “Saturday”
}

To get today week day we need to write a function that returns weekday from current Date:

func getWeekName() -> String{
let formatter:DateFormatter = DateFormatter()
let selectedDate = Date()
formatter.dateFormat = “EEEE”
let weekDay = formatter.string(from: selectedDate )
return weekDay
}

We can use this enum in where ever you want to check week day functionaity as it is globally declared and not in a class. All we need is an instance or otherwise we can directly access via enum name. Here we implemented with the familiar song “nothing to do” just for fun. Enjoy coding.

func toDo(){ //This function would print the text according to today’s Date
switch getWeekName() { //RETURNS WEEK DAY Eg: MONDAY
case Days.Sun.rawValue:
print(“Sunday, I have nothing to do!”)
case Days.Mon.rawValue:
print(“Monday, I have nothing to do!”)
case Days.Tue.rawValue:
print(“Tuesday, I have nothing to do!”)
case Days.Wed.rawValue:
print(“Wednesday, I have nothing to do!”)
case Days.Thur.rawValue:
print(“Thursday, I have nothing to do!”)
case Days.Fri.rawValue:
print(“Friday, I have nothing to do!”)
case Days.Sat.rawValue:
print(“Saturday, I have nothing to do!”)
default:
print(“All time I have nothing to do”)
}
}

Finally call the above method:

self.toDo()

HOW IT WORKS

Here the day from getWeekName() returns week day of today’s date and that string is checked with enum’s rawvalue and the corresponding scope statements get executed. Similary if we want to change the text you can change from one place for all over cheking if we use enum. Otherwise you have to change all over the class where you implemented with raw week day string or anyother date. Try to use globalisation and Keep your code compact.

Happy Coding!❤️

--

--

lyvennitha sasikumar

Passionate iOS developer chasing my dreams toward success