top of page
Home: Blog2
Home: Instagram_Widget

Enumerations

An enumeration is a complete, ordered listing of all the items in a collection. The term is commonly used in mathematics and computer science to refer to a listing of all of the elements of a set / group - so thereby inferring that since its a set it comprises of a group of related values. Enumerations in swift are flexible and can be used to derive an output according to the various cases that are specified in the program and these outputs can be in the form of any type.

Enumerations have the following characteristics which makes them great to use in your code,

ree

So lets have a crack at this by using an example where we create and enum which identifies what the type of day it is - to then use the case approach to then further solve for whether there would be work. We also incorporate the switch to handle the difference scenarios depending on the enum case.

enum WhatTypeOfDay {
    case weekday
    case weekend
    case publicholiday
    case bankholiday
    case nationalEmergencyDay
}

//Initialise the workingDay with weekday
var workingDay = WhatTypeOfDay.weekday
//change the workingday to be bankholiday

switch workingDay {
case .weekday:
    print("Its a working day today")
case .weekend:
    print("Its the weekend, not at work")
case .publicholiday:
    print("Its the public holiday, not at work")
case .bankholiday:
    print("Bank is closed, we are still open for businesss")
default:
    print("what on earth are you thinking today is? go back home! ")

}

In the above example you will see that there is a default handling capability as well. So if we had declared

var workingDay = WhatTypeOfDay.nationalEmergencyDay
// the output would then return the default print statement

Its possible to iterate over an enum and thus is captured in details in the Swift 5.1 Guide. You will need to use the CaseIterable protocol for this and do the count of all the cases by using .allCases.count


The more I think about enums its becoming evident that this is a good way to handle flow control rather than always relying on the if-else statement approach. Depending on the use cases enums could probably handle higher complexity a lot more cleanly. Let start incorporating more in our coding.

Comments


Home: Subscribe

©2019 by CodingWithSuj. Proudly created with Wix.com

bottom of page