0
0
Swiftprogramming~5 mins

Associated values per case in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Associated values per case
O(n)
Understanding Time Complexity

We want to understand how the time it takes to work with enums that have associated values changes as we use more cases or values.

How does the program's work grow when we handle different enum cases with associated data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


enum Device {
    case phone(model: String)
    case tablet(model: String)
    case laptop(model: String)
}

func printDevice(_ device: Device) {
    switch device {
    case .phone(let model):
        print("Phone model: \(model)")
    case .tablet(let model):
        print("Tablet model: \(model)")
    case .laptop(let model):
        print("Laptop model: \(model)")
    }
}

This code defines an enum with associated values and a function that matches each case to print its model.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch statement checks the enum case once per call.
  • How many times: Exactly once for each enum value processed.
How Execution Grows With Input

Each time we call the function with a device, it does one check to find the matching case.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of enum values processed, one check per value.

Final Time Complexity

Time Complexity: O(n)

This means the time to process devices grows in a straight line with how many devices you handle.

Common Mistake

[X] Wrong: "Matching enum cases with associated values takes longer for each case because of the extra data."

[OK] Correct: The switch checks the case once per value, and the associated data is accessed directly without extra loops, so the time per value stays constant.

Interview Connect

Understanding how enum case matching scales helps you explain how your code handles different data efficiently and clearly.

Self-Check

"What if we added a loop inside each case to process the model string character by character? How would the time complexity change?"