PROGRAMMING

Use Enums Effectively

How to properly use enums to model your data

Riccardo Cipolleschi
The Startup
Published in
7 min readDec 29, 2020

--

Swift is an interesting language. It is very friendly for new developers: its syntax is concise and simple to grasp, as well as its main concepts.

However, it takes a lot of time to really master it. Every feature of the language has some details that are deeper than what described in swift.org’s Language Guide.

In today’s article, I’d like to explore some more advanced usages of enums. Enums are extremely powerful and they are often underused or misused. I hope to shed some light on ways to use them that you may have not thought about.

Models Exclusivity

Starting with the simplest idea, enum can be used to express alternatives: you need to choose between running, cycling and swimming? Use an enum! You need to list the days of the week? Use an enum!

These are the simplest cases. However, Swift’s enums are more powerful than that. Enums support associated values, that are data related to a specific instance. For example, the running case can include the number of steps performed, the cycling case can include the gear used during the workout and the swimming session could be influenced by the water temperature.

--

--

Riccardo Cipolleschi
The Startup

Hey there, I’m Riccardo. Software engineer at Meta. I have a passion for iOS and I love to share my knowledge with others.