0
0
Swiftprogramming~15 mins

Enum declaration and cases in Swift - Deep Dive

Choose your learning style9 modes available
Overview - Enum declaration and cases
What is it?
An enum in Swift is a way to group related values under a single type name. Each value inside an enum is called a case. Enums help organize code by giving meaningful names to a set of options or states. They make your code easier to read and less error-prone.
Why it matters
Enums exist to clearly represent a fixed set of choices or states in your program. Without enums, you might use numbers or strings that can be confusing or incorrect. Enums prevent mistakes by limiting values to only those defined, making your code safer and easier to understand.
Where it fits
Before learning enums, you should know about basic Swift types like strings, integers, and variables. After enums, you can learn about associated values, raw values, and how enums work with switch statements to handle different cases.
Mental Model
Core Idea
An enum is like a labeled box that can hold exactly one value from a set of named options.
Think of it like...
Imagine a vending machine with buttons labeled for each snack. Pressing a button selects exactly one snack from the available choices. The enum is the vending machine, and each case is a button for a snack.
Enum Example:
┌───────────────┐
│   Enum Type   │
│  Beverage     │
├───────────────┤
│ case coffee   │
│ case tea      │
│ case juice    │
└───────────────┘

You pick one case at a time, like pressing one button.
Build-Up - 6 Steps
1
FoundationBasic enum declaration syntax
🤔
Concept: How to declare a simple enum with cases in Swift.
In Swift, you declare an enum using the keyword 'enum' followed by the name and a list of cases inside curly braces. Each case represents a possible value. Example: enum Direction { case north case south case east case west }
Result
You create a new type called Direction with four possible values: north, south, east, and west.
Knowing the basic syntax lets you define your own types that group related options clearly and safely.
2
FoundationUsing enum cases in code
🤔
Concept: How to create and use enum values in variables.
You can create a variable of the enum type and assign one of its cases. Example: var travelDirection = Direction.north You can also change it: travelDirection = .east // shorthand when type is known
Result
The variable travelDirection holds a value that can only be one of the enum's cases.
Enums restrict values to a fixed set, preventing invalid assignments and making your code more predictable.
3
IntermediateEnums with multiple cases on one line
🤔
Concept: How to declare multiple cases in a compact way.
Swift lets you list multiple cases on one line separated by commas. Example: enum CompassPoint { case north, south, east, west }
Result
The enum CompassPoint has the same four cases but declared more compactly.
This syntax helps keep your code clean and readable when you have many simple cases.
4
IntermediateSwitching over enum cases
🤔Before reading on: do you think you can use if-else or switch to handle enum cases? Which is better for many cases?
Concept: How to use switch statements to perform different actions based on enum values.
Switch statements let you check the enum value and run code for each case. Example: switch travelDirection { case .north: print("Going north") case .south: print("Going south") case .east: print("Going east") case .west: print("Going west") }
Result
The program prints a message depending on the current enum case.
Switching on enums ensures you handle all possible cases explicitly, reducing bugs.
5
AdvancedEnums with associated values
🤔Before reading on: do you think enum cases can hold extra information? How might that work?
Concept: Enums can store extra data with each case, making them more flexible.
You can add associated values to enum cases to hold extra information. Example: enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } let productBarcode = Barcode.upc(8, 85909, 51226, 3) let qr = Barcode.qrCode("XYZ123")
Result
Each enum case can carry different types and amounts of data, making enums powerful for complex data.
Understanding associated values unlocks enums as versatile containers, not just fixed labels.
6
ExpertRaw values and automatic assignment
🤔Before reading on: do you think enum cases can have default values? How does Swift assign raw values automatically?
Concept: Enums can have raw values like strings or integers, which can be assigned automatically or manually.
You can assign raw values to enum cases, which are constant values of the same type. Example: enum Planet: Int { case mercury = 1 case venus case earth case mars } Here, venus gets raw value 2 automatically, earth 3, and so on. You can access raw values with .rawValue and create enums from raw values with init?(rawValue:).
Result
Raw values let enums connect to external data like numbers or strings, useful for storage or communication.
Knowing raw values helps integrate enums with other systems and simplifies data conversion.
Under the Hood
Swift enums are implemented as a special type that can hold exactly one of its defined cases at a time. Internally, the compiler assigns a small amount of memory to store which case is active and any associated data. When you use switch statements, the compiler can optimize to jump directly to the matching case code. Raw values are stored as constants linked to each case, allowing fast lookup and conversion.
Why designed this way?
Enums were designed to provide a safe, clear way to represent a fixed set of options. The ability to have associated values and raw values makes them flexible for many uses, from simple labels to complex data containers. This design balances safety, expressiveness, and performance, avoiding errors common with loose constants or strings.
Enum Storage and Usage:

┌───────────────┐
│   Enum Value  │
│ ┌───────────┐ │
│ │ Case Tag  │ │  <-- Stores which case is active
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Associated│ │  <-- Optional extra data per case
│ │  Values   │ │
│ └───────────┘ │
└───────────────┘
       ↓
┌─────────────────────┐
│ Switch Statement     │
│ Matches Case Tag     │
│ Executes Case Code   │
└─────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Can enum cases be changed after you create them? Commit to yes or no.
Common Belief:Enum cases are like variables and can be changed freely anytime.
Tap to reveal reality
Reality:Enum cases are fixed values; you can assign a variable to a case, but the case itself is constant and cannot be changed.
Why it matters:Thinking enum cases are mutable leads to confusion and bugs when trying to modify them like variables.
Quick: Do all enum cases have to have the same type of associated value? Commit to yes or no.
Common Belief:All enum cases must have the same type or no associated values at all.
Tap to reveal reality
Reality:Each enum case can have different types and numbers of associated values, making enums very flexible.
Why it matters:Believing this limits how you design enums and prevents using their full power for complex data.
Quick: Does Swift automatically assign raw values to string enums like it does for integer enums? Commit to yes or no.
Common Belief:Swift automatically assigns raw string values to enum cases if you don't specify them.
Tap to reveal reality
Reality:Swift only automatically assigns raw values for integer and some other types, but for strings you must assign them explicitly.
Why it matters:Assuming automatic string raw values can cause runtime errors or unexpected nil values.
Expert Zone
1
Enums with associated values are implemented as tagged unions, allowing different data shapes per case, which is a powerful pattern for modeling complex state.
2
Raw values and associated values are mutually exclusive; you cannot have both on the same enum case, which influences design choices.
3
Swift enums support recursive cases with the 'indirect' keyword, enabling data structures like trees or linked lists to be modeled cleanly.
When NOT to use
Avoid enums when you need a dynamic or open-ended set of values that can change at runtime; use classes or structs instead. Also, if you need inheritance or shared behavior beyond what enums support, classes are better.
Production Patterns
In real-world Swift apps, enums are widely used for state machines, error handling with Result types, and representing API response types. They often combine with switch statements and pattern matching for clear, safe code flow.
Connections
Algebraic Data Types (ADTs)
Enums in Swift are a form of ADTs, combining fixed cases with optional data.
Understanding enums as ADTs connects programming to mathematical type theory, explaining their power and limitations.
Finite State Machines
Enums model states in a finite state machine, where each case is a state.
Knowing this helps design clear state transitions and logic in apps like games or UI flows.
Human Decision Making
Enums represent a fixed set of choices, similar to how people choose from limited options in daily life.
This connection shows how programming models real-world decisions, making code more intuitive.
Common Pitfalls
#1Trying to assign a value to an enum case like a variable.
Wrong approach:Direction.north = .south
Correct approach:var direction = Direction.north direction = .south
Root cause:Confusing enum cases (which are constants) with variables that can change.
#2Forgetting to handle all enum cases in a switch statement.
Wrong approach:switch direction { case .north: print("North") // missing other cases }
Correct approach:switch direction { case .north: print("North") case .south: print("South") case .east: print("East") case .west: print("West") }
Root cause:Not realizing that missing cases can cause runtime errors or warnings.
#3Assuming raw string values are assigned automatically.
Wrong approach:enum Color: String { case red case green case blue } print(Color.red.rawValue) // nil or error
Correct approach:enum Color: String { case red = "red" case green = "green" case blue = "blue" } print(Color.red.rawValue) // "red"
Root cause:Misunderstanding Swift's raw value assignment rules.
Key Takeaways
Enums group related values under a single type, making code safer and clearer.
Each enum case is a fixed option, and variables of enum type can only hold those cases.
Enums can carry extra data with associated values, making them versatile containers.
Raw values connect enum cases to external data like numbers or strings, aiding integration.
Switch statements with enums enforce handling all cases, reducing bugs and improving clarity.