0
0
Swiftprogramming~5 mins

Closures are reference types in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures are reference types
O(n)
Understanding Time Complexity

When working with closures in Swift, it's important to understand how their reference nature affects performance.

We want to see how the cost of using closures grows as we create or call more of them.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    func makeIncrementer(amount: Int) -> () -> Int {
        var total = 0
        let incrementer: () -> Int = {
            total += amount
            return total
        }
        return incrementer
    }

    let incrementByTen = makeIncrementer(amount: 10)
    for _ in 1...n {
        _ = incrementByTen()
    }
    

This code creates a closure that adds a fixed amount each time it is called, then calls it n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the closure inside the loop.
  • How many times: The closure is called n times, once per loop iteration.
How Execution Grows With Input

Each time we call the closure, it performs a simple addition and returns a value.

Input Size (n)Approx. Operations
1010 additions and returns
100100 additions and returns
10001000 additions and returns

Pattern observation: The number of operations grows directly with n, the number of times the closure is called.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as we call the closure more times.

Common Mistake

[X] Wrong: "Closures are simple values, so calling them many times is always constant time."

[OK] Correct: Each closure call runs code, so calling it n times means n operations, not just one.

Interview Connect

Understanding how closures behave as reference types helps you reason about performance and memory in real apps.

Self-Check

What if we created a new closure inside the loop each time instead of calling the same one? How would the time complexity change?