DEV Community

Gamya
Gamya

Posted on

Swift Enums

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"
Enter fullscreen mode Exit fullscreen mode

Later in the code you update it:

currentArc = "Pain Invasion"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Now instead of a freeform string, you use one of those exact cases:

var currentArc = NarutoArc.chuninExams
currentArc = NarutoArc.painInvasion
Enter fullscreen mode Exit fullscreen mode

Try to use something that doesn't exist:

currentArc = NarutoArc.randomMadeUpArc // โŒ ERROR โ€” Swift refuses to compile
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 ๐Ÿ˜ค
Enter fullscreen mode Exit fullscreen mode

Now imagine if this was strings:

var sasukesAttack = "Magic"
sasukesAttack = "Ultimte" // Typo โ€” Swift won't catch it, but your game will break
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Output:

Sasuke is using: standard
Sasuke switched to: chidoriStream
Enter fullscreen mode Exit fullscreen mode

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)