How to correctly model data in Swift

Swift: Enumerations

Use cases and Implementation

Navdeep Singh
May 31, 2020 · 6 min read

In this article, we’re going to learn about enumerations in Swift or as they’re more commonly known, enums.

Enumerations are used to model a finite dataset and found commonly in different programming languages. In Swift its history can be traced back to C language but enumerations in Swift are a lot more flexible.

Why Enumerations: the problem

Swift offers multiple ways to model data to be used in a program. We can use object and collections to do that. But there is certain kinds of data where normal objects and collections don’t quite suffice the need.

But what is the issue with normal data types? Let’s understand with help of the following example:

Let’s say we want to model a typical year for a calendar app. To achieve this we can simply declare and array of String type and name it months as follows:

Array of months

So far so good, right? Based on the knowledge of collections it is safe to assume that an array is the best choice here since we only need to identify what month of the year it is.

Now let’s see what happens when we try to use this data.

Say, our calendar app tries to generate a notification if the given month is in spring season.

Table to show months and seasons

Let’s consider the following calendar to decide if a month is in spring or not.

If the given month is within a season as described in table then the function will return respective season, for example for January the function should return Winter.

If an invalid month is passed in as an argument to the function then the function should return Invalid month since our table does not recognise anything other than the given twelve months. Our function will be written as follows:

Function to get respective season for a given month

Notice how careful the developer has to be while calling the function. If call to the function has a typo in it, the outcome would be totally different from expectation and that makes this logic really unreliable. For example, let’s assume that the developer using above function wanted to know the result for “April” but instead of passing in “April” as a string he/she made a typo and passed in “Arpil” to the function which would result “Invalid month” as the outcome and not what he/she would have expected.

Also, imagine if the logic of the function itself had a flaw in it because of a typo and instead of checking “September” in the fourth case, we were checking for “Setpember” as follows:

Function to get respective season for a given month with typo

In this scenario even if the call to the function is made with correct arguments, the function will never return expected result as shown in the following screenshot:

Function logic is incorrect because of the error in typing.

Enumerations to the rescue

In the previous section we noticed that the path we took was fraught with peril.

So how can we solve this? and make use of Swift’s type safety to help us at compile time to make sure that we aren’t doing anything terribly wrong.

Solution to the problem

Let’s try and solve the same problem but get rid of those strings altogether and use an enum. This time, instead of an array of months, we will create an enum named Month as follows:

Enumeration for Months

Inside the body of this enum, we have defined member values. Each month of the year is a different member. We can now use this datatype in the our previous function as follows:

func season(for month: Month) -> String {}

and since the values inside enumeration are finite, when we switch over month inside the function you will notice that we don’t require the default case:

Function to get respective season for a given month with Enum

also, while using the member values you’ll notice something interesting. The moment you put that dot next to Month and start typing, Xcode starts auto completing for us as shown in the image below:

Compiler auto-suggesting the option from enum member values.

There’s that compiler help we were hoping for earlier.

We simply use the type, a dot, and then it’s like we’re accessing a property. Now, let’s say I typed Setpember, like that mistake we made earlier. Well, because this is an actual value and not a string, we typed value, you’ll notice that the compiler complains that the enum case isn’t found as shown below:

Compiler complaining about the incorrectly typed member type

Hence with the compiler help, we’ve eliminated the possibility of typing an incorrect value.

Why don’t we need a default case in this scenario?

The switch statement is exhaustive by nature which means that it needs to covers all possible paths for the value of the type on which we are switching the control.

In the earlier scenario when we were switching on the String type a default case was required as we only covered names of the months in custom cases leaving behind a plethora of other possibilities. So, a default case was required to handle all those possibilities but in the second scenario since we were only switching on a finite set of data we did not require a default statement as all the possible cases were covered by custom cases.

The compiler keeps a close eye on what we’re doing. For example, if we remove this Month.April case, the compiler immediately knows that all paths aren’t considered, and complains that the switch statement must be exhaustive as shown below:

Switch must be exhaustive

We can either add a case for April or a default case to fix this.

Adding a computed property to the Enumeration

Another way in which we can eliminate the requirement for a separate function season is by adding a computed property to the enumeration. So we will replace the following function:

func season(for month: Month) -> String {}

with the computed property season as shown in the code block below:

Now, we can simply use the computed property on the enumeration as follows:

Using computed property instead of the function

Conclusion

In this article, we discussed about Enumerations in Swift. We briefly discussed how enumerations can help in solving certain programming issues and write bug free code.

In the beginning of the chapter we mentioned that Swift enums are very powerful when compared to many other languages. We will cover some of those features in upcoming articles, like the raw representable form, associated values and protocol conformance.

Thanks for reading, please share it if you found it useful 🙂

For other updates you can follow me on Twitter on my twitter handle @NavRudraSambyal.

The Startup

Get smarter at building your thing. Join The Startup’s +794K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Navdeep Singh

Written by

Author of Reactive programming with Swift, Senior Software Engineer — Exploring possibilities with new Tech.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +794K followers.

Navdeep Singh

Written by

Author of Reactive programming with Swift, Senior Software Engineer — Exploring possibilities with new Tech.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +794K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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