Enums in Swift

An enumeration type appears in every programming language, Enum stores the finite set of data like string, integer, enum is a list of comprehensive raw data in swift, enum is useful for handling flag, states, choices with respect of object and functionality. enum type plays a very important role in development to handle the lifecycle of operations and many more.

let us see, how enum works in swift, enum is declared by enum keyword, with enum type variable name, by using case keyword you can define values in the enum, here is how enum is declared in swift.

StatusType enum doesn’t represent any ideal characteristics of any of the individual case, it just represents the Status type, we can return raw value in term of the particular type case, here is how we can represent value for listed cases.

you can return value of enum type case.

As we discussed, we can handle functionality as per status or choice of an object, We can handle enum type in switch case conditions also, to perform an operation with respect to the particular case.

Descriptive enum:

We have applied raw value to enum which is Int32 data type, we can send this value to web service or store in core data, what if we want to have the descriptive value of the enum cases, we can write a function inside enum to get the descriptive value of respective enum case, here I have an example

Now i will try to fetch descriptive value of an particular enum case.

Identical type Enum cases:

Do not worry, I will explain to you briefly how to implement identical test cases. enum doesn’t associate raw value, we can have a different identical value of each case. let us start with an example, we will track Task Status by identical enum type cases.

First we will create one model for Task.

Create type enum with identical values. here we are giving different input values for different cases like.

1) OPEN : open will not have input value.

2) STARTED: The started case will have Date() input value, which will be the task Started Date.

3) SUSPENDED: Suspended Case will have string input values, which will be the reason for suspension.

4) COMPLETED: Completed Case will have Date() input values, which will be the date of task completion.

5) CANCELED: Canceled Case will have string input values, which will be the reason for cancelation.

Create model for handle task status. Default StatusType declared as .OPEN

Implemented update StatusType function below, which will perform the operation of regarded enum case.

Here is how identical enum updating task status model

CaseIterable:

CaseIterable is a protocol returns all values of collection. CaseIterable protocol can be conformed to the enum.

Conclusion:

Enum is an extreme and adaptable type in swift, enum plays a significant role in data binding while developing Swift Application. Handle states, flags, and thought code architecture, There are many more protocols that can conform with enum type like equatable.

Leave a Comment