So far in this series we've stored data using strings, integers, arrays, dictionaries, and sets. But what happens when you want to store a value that can only ever be one of a fixed list of options? ๐ค
That's exactly what enums are for.
๐ฌ The Problem โ Strings Are Dangerous
Let's say you're building an app that tracks which arc a user is currently watching in Naruto. You might start with a simple string:
var currentArc = "Chunin Exams"
Later in the code you update it:
currentArc = "Pain Invasion"
That looks fine. But what about this?
currentArc = "pain invasion" // lowercase โ different string!
currentArc = "Pain Invasoin" // typo โ Swift won't catch this
currentArc = "Chunin Exams " // trailing space โ silently wrong
Swift won't complain about any of these. They're all valid strings. But your app logic will break in confusing, hard-to-debug ways because you made a tiny human mistake.
And beyond safety, strings are also inefficient. Do you really need to store all 13 characters of "Pain Invasion" just to track which arc someone is on? There has to be a better way. ๐ง
โ Enter Enums
An enum (short for enumeration) lets you define a brand new data type with a fixed list of possible values โ called cases. You decide exactly what's allowed, and Swift enforces it for you.
Here's the arc tracker rewritten as an enum:
enum NarutoArc {
case chuninExams
case invasion
case painInvasion
case fourthGreatWar
case boruto
}
Now instead of a freeform string, you use one of those exact cases:
var currentArc = NarutoArc.chuninExams
currentArc = NarutoArc.painInvasion
Try to use something that doesn't exist:
currentArc = NarutoArc.randomMadeUpArc // โ ERROR โ Swift refuses to compile
Swift catches the mistake before your app even runs. That's the power of enums. ๐
๐งน Cleaner Syntax
When you have lots of cases, you don't need to write case on every line โ just separate them with commas:
enum NarutoArc {
case chuninExams, invasion, painInvasion, fourthGreatWar, boruto
}
And once Swift knows the type of your variable, you can drop the enum name entirely in future assignments:
var currentArc = NarutoArc.chuninExams // Swift now knows this is a NarutoArc
currentArc = .painInvasion // โ
No need to repeat NarutoArc
currentArc = .fourthGreatWar // โ
Clean and readable
Swift knows that .painInvasion must mean NarutoArc.painInvasion because currentArc can only ever be a NarutoArc. Less typing, same safety ๐ธ
โก Enums Are More Efficient Than Strings
Here's something that isn't immediately obvious โ enums are actually much faster and lighter than strings under the hood.
When you write NarutoArc.painInvasion, Swift stores that as a simple number internally โ something like 2. Compare that to storing the actual string "painInvasion" โ that's 12 characters taking up real memory.
So enums give you:
- โ Human-readable names in your code
- โ Tiny, efficient storage behind the scenes
- โ Zero chance of typos or invalid values
๐บ๏ธ Another Example โ Directions
A classic enum example that makes the benefit super clear:
enum Direction {
case north
case south
case east
case west
}
Without enums you might use integers โ 1 for north, 2 for south, and so on. But who remembers what 3 means? And what stops someone from typing 5 by mistake?
var heading = Direction.north
heading = .west
heading = .south
This is instantly readable. No magic numbers. No guessing. Swift knows exactly what's valid and what isn't. ๐งญ
๐ฎ A Real-World Example
Let's build something more practical โ a simple battle system for an RPG:
enum AttackType {
case physical
case magic
case ranged
case ultimate
}
var sasukesAttack = AttackType.magic
sasukesAttack = .ultimate
var narutosAttack = AttackType.physical
narutosAttack = .ultimate // He saved his Rasengan for last ๐ค
Now imagine if this was strings:
var sasukesAttack = "Magic"
sasukesAttack = "Ultimte" // Typo โ Swift won't catch it, but your game will break
Enums make this kind of logic bulletproof. Your IDE (Xcode) will even show you a list of all valid cases the moment you type the dot โ no documentation needed. ๐ฏ
๐ String vs Enum โ Side by Side
| String | Enum | |
|---|---|---|
| Typo protection | โ None | โ Compile-time error |
| Autocomplete in Xcode | โ No | โ Yes |
| Storage efficiency | โ Stores every character | โ Stored as a simple number |
| Fixed set of options | โ Anything goes | โ Only your defined cases |
| Readability | โ ๏ธ Okay | โ Crystal clear |
๐งฉ Putting It All Together
Here's a mini example combining everything:
enum ChidoriVariant {
case standard
case chidoriSharp
case chidoriStream
case chidoriSenbon
}
var sasukesCurrentMove = ChidoriVariant.standard
print("Sasuke is using: \(sasukesCurrentMove)")
sasukesCurrentMove = .chidoriStream
print("Sasuke switched to: \(sasukesCurrentMove)")
// Try to use an invalid case
// sasukesCurrentMove = .rasengan โ โ Swift won't allow it
Output:
Sasuke is using: standard
Sasuke switched to: chidoriStream
Clean, safe, and impossible to break with a typo ๐ฅ
๐ Wrap Up
Enums solve a real problem โ they stop you from making subtle, hard-to-catch mistakes with freeform values like strings or magic numbers.
Here's what to remember:
- Enums define a fixed list of valid values โ nothing outside that list is allowed
- Swift catches invalid cases at compile time โ before your app even runs
- You can skip the enum name after the first assignment โ just use
.caseName - Behind the scenes, enums are stored as simple numbers โ fast and memory-efficient
- Xcode gives you full autocomplete on enum cases โ no typos possible
And this is just the beginning โ as you go deeper into Swift you'll discover that enums can do far more than what we've covered here. They are arguably one of Swift's most powerful features, and you'll see them absolutely everywhere in real iOS codebases. ๐ช
Next up, we'll look at type annotations โ telling Swift explicitly what type a variable should be. See you there! ๐
Top comments (0)