0
0
Swiftprogramming~5 mins

Closure expression syntax in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closure expression syntax
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a closure expression changes as the input grows.

We want to know how the number of operations grows when using closure expressions in Swift.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { (number: Int) -> Int in
    return number * 2
}
print(doubled)

This code uses a closure expression inside the map function to double each number in the array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The closure runs once for each element in the array.
  • How many times: Exactly as many times as there are elements in numbers.
How Execution Grows With Input

Each element causes the closure to run once, so the total work grows with the number of elements.

Input Size (n)Approx. Operations
1010 closure calls
100100 closure calls
10001000 closure calls

Pattern observation: The work grows directly in proportion to the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the closure grows linearly with the number of items in the array.

Common Mistake

[X] Wrong: "The closure runs only once no matter the array size."

[OK] Correct: The closure is called for each element, so more elements mean more calls.

Interview Connect

Understanding how closures run over collections helps you explain performance clearly in real coding situations.

Self-Check

What if we replaced map with filter using a closure? How would the time complexity change?