0
0
Swiftprogramming~5 mins

Capture lists in closures in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Capture lists in closures
O(n)
Understanding Time Complexity

When using capture lists in closures, it is important to understand how the closure accesses variables and how often it runs. This helps us see how the program's work grows as input changes.

We want to know how the closure's execution time changes with the size of captured data or repeated calls.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    func makeIncrementer(amount: Int) -> () -> Int {
        var total = 0
        return { [amount] in
            total += amount
            return total
        }
    }
    
    let incrementByFive = makeIncrementer(amount: 5)
    print(incrementByFive())
    print(incrementByFive())
    

This code creates a closure that captures a constant value and updates a variable each time it runs.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The closure increments a variable and returns it each time it is called.
  • How many times: Each call to the closure runs the increment operation once.
How Execution Grows With Input

The closure runs a simple addition each time it is called, regardless of input size.

Input Size (n)Approx. Operations
10 calls10 additions
100 calls100 additions
1000 calls1000 additions

Pattern observation: The work grows directly with the number of times the closure is called, one addition per call.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows linearly with the number of closure calls.

Common Mistake

[X] Wrong: "The capture list makes the closure run faster or slower depending on the size of captured variables."

[OK] Correct: The capture list only controls how variables are captured, not how many times the closure runs or how much work each call does.

Interview Connect

Understanding how closures capture variables and how that affects repeated execution helps you reason about performance in real Swift code. This skill shows you can think about both code behavior and efficiency.

Self-Check

What if the closure captured a large array instead of a single integer? How would the time complexity change when calling the closure multiple times?