PROGRAMMING
Use Enums Effectively
How to properly use enums to model your data
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 enum
s. Enum
s 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. Enum
s 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.