SWIFT ENUMERATIONS

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:

Syntax:

USAGE:

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:

HOW IT WORKS

Happy Coding!❤️

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store