Hiker scared in the forest

Swift Enums — A story about choices

Keith Elliott (keithelliott.co)
11 min readApr 18, 2024

--

Introduction

Swift enums are powerful. I'll explain a few basic usages and then step things up with less apparent uses that will change how you write your code, providing more type safety and simplifying code that would otherwise create a spaghetti-noodle mess.

What if you had to create code to evaluate two conditions and react accordingly with expressions ("then here's what I do code")? The base if-else formula handles this nicely. All is good when there are only two or a handful of conditions for which you want to react. You can even evaluate string matches as the condition.

But there is a gotcha when testing for string equality with conditional branching that will bite you at some point during your coding adventures. In fact, several side effects could be hidden time bombs lying in wait, ready to jump you in the dark to capitalize on your typos and small mistakes, any of which could be hard to spot at first glance. When it happens to you, you'll be perturbed that the if-else formula you have grown so accustomed to writing betrayed you.

However, there is another way to reduce the chances of writing conditional code that is clearer to read and less error-prone. I'm curious. Skeptical. I thought so, but work with me here. It's not a catchall but a new tool for the toolbelt.

--

--

Keith Elliott (keithelliott.co)

Tech vet, 20+ yrs from dev to CTO, startup enthusiast, husband, father of 5 + foster child. Eager to empower startups and motivate devs, thriving amid chaos.