DEV Community

Agoi Abel Adeyemi
Agoi Abel Adeyemi

Posted on

Enums in Swift with Real Life Examples

Introduction

Enumeration (Enum) defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Assuming we have a method named dayType that accept any day of the week then return Weekend for Saturday and Sunday, Weekday for Monday, Tuesday, Wednessday, Thursday and Friday and return This is not a valid date when it fails to recognised what was been passed into it. The function will work as aspected but what happens when you actually want to pass let say a friday but you mistakingly type fridaysy even though what we actually wanted to type was friday. The switch above goes to the default This is not a valid date. That is the type-safty enum brings into the table. It help us to avoid such risk by providing common type for group of related values like below:

We have been able to eliminate the use of String by defining an enum to hold the days. We don’t need to use the append the Day before every declaration of the day enum within the switch statement because we already assigned day to be a type of Day. Hence the dayType function can be reduce to below:

We have to understand enum is best suited for declaring types with finite sets of possible states, like Direction (north, south, west, east), Movement (Up, down, left, right) etc.

Enum Values

We can assign value to each enum case. This is useful if the enum itself indeed relates to something

We can access the value assigned to an enum with the rawValue keyword. To access the Week enum above, we can use Week.Monday.rawValue which will return Weekday.

Enum Associate Values

Associate values are a fantastic way of attaching additional information to an enum case. Say you’re writing a trade engine, there are two different possible trade types, Buy and Sell that will have a specific stock and amount. We can represent this using associate enum values like below

Associate values are a fantastic way of attaching additional information to an enum case. Say you’re writing a trade engine, there are two different possible trade types, Buy and Sell that will have a specific stock and amount. We can represent this using associate enum values like below

Enum Methods

We can also define methods on an enum like below

Notice the code snippet above, the func description will return "This is an apple device" for every case in the enum. To avoid this, we can make use of switch statement within the description method like below

I am happy to share this article with you. If you’ve enjoyed this article, do show support loving it 👏 . Thanks for your time and make sure to follow me or drop your comment below 👇

Top comments (0)