Bird
Raised Fist0
Swiftprogramming~15 mins

Enum declaration and cases in Swift - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the purpose of an enum in Swift?
easy
A. To group related values under one name
B. To create a function
C. To declare a variable
D. To write a loop

Solution

  1. Step 1: Understand what enums represent

    Enums group related values together to make code clearer and safer.
  2. Step 2: Compare options with enum purpose

    Only To group related values under one name correctly describes grouping related values under one name.
  3. Final Answer:

    To group related values under one name -> Option A
  4. Quick Check:

    Enum purpose = Group related values [OK]
Hint: Enums group related values clearly and safely [OK]
Common Mistakes:
  • Confusing enums with functions
  • Thinking enums declare variables
  • Mixing enums with loops
2. Which of the following is the correct way to declare an enum named Direction with cases north, south, east, and west?
easy
A. enum Direction = { north, south, east, west }
B. enum Direction: north, south, east, west {}
C. enum Direction { case north, south, east, west }
D. enum Direction { north; south; east; west }

Solution

  1. Step 1: Recall Swift enum syntax

    Enums use the keyword enum, followed by the name and curly braces containing case declarations separated by commas.
  2. Step 2: Check each option's syntax

    enum Direction { case north, south, east, west } uses correct syntax: enum Direction { case north, south, east, west }. Others use invalid syntax.
  3. Final Answer:

    enum Direction { case north, south, east, west } -> Option C
  4. Quick Check:

    Correct enum syntax = enum Direction { case north, south, east, west } [OK]
Hint: Use 'case' keyword with comma-separated values inside braces [OK]
Common Mistakes:
  • Using '=' instead of braces
  • Omitting 'case' keyword
  • Separating cases with semicolons
3. What will be the output of this Swift code?
enum Light {
    case red, yellow, green
}

let current = Light.red
switch current {
case .red:
    print("Stop")
case .yellow:
    print("Caution")
case .green:
    print("Go")
}
medium
A. No output
B. Go
C. Caution
D. Stop

Solution

  1. Step 1: Identify the enum case assigned

    The variable current is assigned Light.red.
  2. Step 2: Match the switch case for current

    The switch matches .red and prints "Stop".
  3. Final Answer:

    Stop -> Option D
  4. Quick Check:

    Light.red triggers "Stop" output [OK]
Hint: Match enum case in switch to get output [OK]
Common Mistakes:
  • Confusing enum cases with strings
  • Forgetting dot prefix in switch
  • Assuming default output
4. Identify the error in this enum declaration:
enum Weather {
    case sunny
    case rainy
    case windy
    case
}
medium
A. Missing case name after 'case' keyword
B. Enum name is invalid
C. Curly braces are missing
D. Enum cases should be strings

Solution

  1. Step 1: Review each enum case line

    The last line has case without a case name, which is invalid syntax.
  2. Step 2: Confirm other parts are correct

    Enum name and braces are correct; cases do not need to be strings.
  3. Final Answer:

    Missing case name after 'case' keyword -> Option A
  4. Quick Check:

    Every 'case' must have a name [OK]
Hint: Each 'case' must have a name after it [OK]
Common Mistakes:
  • Leaving 'case' empty
  • Thinking cases need quotes
  • Missing braces around enum
5. You want to create an enum Planet with cases for mercury, venus, and earth. Then, write a function that returns a friendly message for each planet. Which code correctly implements this?
hard
A. enum Planet { mercury, venus, earth } func message(planet: Planet) -> String { if planet == mercury { return "Closest to the Sun" } else if planet == venus { return "Second planet" } else { return "Our home" } }
B. enum Planet { case mercury, venus, earth } func message(for planet: Planet) -> String { switch planet { case .mercury: return "Closest to the Sun" case .venus: return "Second planet" case .earth: return "Our home" } }
C. enum Planet { case mercury, venus, earth } func message(planet: Planet) -> String { if planet == mercury { return "Closest to the Sun" } else if planet == venus { return "Second planet" } else { return "Our home" } }
D. enum Planet { case mercury, venus, earth } func message(for planet: Planet) -> String { switch planet { case mercury: return "Closest to the Sun" case venus: return "Second planet" case earth: return "Our home" } }

Solution

  1. Step 1: Check enum declaration syntax

    Options A, C, and D declare enum correctly with case keyword; B misses it, so B is invalid.
  2. Step 2: Check function parameter and switch usage

    enum Planet { case mercury, venus, earth } func message(for planet: Planet) -> String { switch planet { case .mercury: return "Closest to the Sun" case .venus: return "Second planet" case .earth: return "Our home" } } uses switch with dot syntax for cases and correct function signature. enum Planet { case mercury, venus, earth } func message(planet: Planet) -> String { if planet == mercury { return "Closest to the Sun" } else if planet == venus { return "Second planet" } else { return "Our home" } } uses if-else without dot syntax (.mercury), causing compile error. enum Planet { case mercury, venus, earth } func message(for planet: Planet) -> String { switch planet { case mercury: return "Closest to the Sun" case venus: return "Second planet" case earth: return "Our home" } } misses dot prefix in switch cases, causing error.
  3. Final Answer:

    enum Planet { case mercury, venus, earth } func message(for planet: Planet) -> String { switch planet { case .mercury: return "Closest to the Sun" case .venus: return "Second planet" case .earth: return "Our home" } } -> Option B
  4. Quick Check:

    Enum with 'case' and switch with dot cases [OK]
Hint: Use 'case' keyword and dot prefix in switch cases [OK]
Common Mistakes:
  • Omitting 'case' keyword in enum
  • Missing dot prefix in switch cases
  • Using if without dot prefix for enum cases
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard