Chapter 74: Swift Enums & Pattern Matching

1. Why do we even need enums? (the most important intuition)

In real life we often have a fixed number of possible states or categories:

  • The weather is either sunny, cloudy, rainy, snowy…
  • User role is admin, moderator, member, guest…
  • Payment status is pending, processing, completed, failed…
  • App screen state is loading, success, error, empty…

In old languages people usually use:

  • strings (“admin”, “moderator”)
  • integers (0 = pending, 1 = completed)
  • booleans (isAdmin = true/false)

All of these are dangerous because:

  • You can write typos (“admnin”)
  • You can pass wrong numbers (status = 999)
  • You can mix unrelated states
  • The compiler cannot help you remember all cases

Swift enums solve all of this.

An enum says: “This value can be one of these exact possibilities — and nothing else.”

The compiler forces you to handle every case (exhaustiveness checking).

That is the single most important superpower of Swift enums.

2. Basic enum — the simplest form

Swift
Swift

Key points:

  • Cases start with lowercase (convention)
  • You always write .caseName when using the value
  • switch must be exhaustive → compiler error if you forget a case

3. Enum with associated values (very powerful — real game changer)

Very often the state needs to carry extra information.

Swift

Real-life example — network / API response (extremely common)

Swift

4. Enum with raw values (when you need to map to String / Int)

Swift

String raw value (very common for API endpoints, JSON keys)

Swift

5. Pattern Matching — the real superpower of Swift enums

Pattern matching is what makes enums so powerful. You can destructure and extract associated values very elegantly.

Basic pattern matching in switch

Swift

Pattern matching in if / guard

Swift

Very powerful real pattern — unwrap + check at once

Swift

6. Very Common Real-Life Examples You Will Write

Example 1 – API response handling (probably the #1 enum use-case)

Swift

Example 2 – Navigation / app state (very common in SwiftUI/UIKit)

Swift

7. Quick Summary – When to use what

Situation Use this kind of enum Typical example
Simple fixed states enum Direction { case north, south, east, west } UI states, weather, roles
State + extra data case success(data: T) API responses, async results
Error with details case failure(code: Int, message: String) Network, validation errors
Raw value needed (String/Int) enum HTTPStatus: Int { case ok = 200 … } API codes, persistence
Need exhaustive checking switch without default on enum Compiler forces you to handle all cases

8. Small Practice – Try these

  1. Create enum PaymentStatus with cases:
    • pending
    • processing(amount: Double)
    • completed(transactionID: String)
    • failed(reason: String)
  2. Write a function that switches on it and prints appropriate message
  3. Create enum APIResult<T> with success(T), failure(String) → Use pattern matching to handle both cases

Paste your code here if you want feedback or want to see more elegant versions!

What would you like to explore next?

  • Advanced pattern matching (if case let, guard case let, switch on tuples…)
  • Enums with associated values in depth
  • RawRepresentable enums (String/Int backed)
  • Enums in SwiftUI (state management, view switching)
  • Or move to another topic (optionals, arrays, map/filter/reduce, protocols…)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *