Closure expression syntax in Swift - Time & Space 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.
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 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.
Each element causes the closure to run once, so the total work grows with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 closure calls |
| 100 | 100 closure calls |
| 1000 | 1000 closure calls |
Pattern observation: The work grows directly in proportion to the input size.
Time Complexity: O(n)
This means the time to run the closure grows linearly with the number of items in the array.
[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.
Understanding how closures run over collections helps you explain performance clearly in real coding situations.
What if we replaced map with filter using a closure? How would the time complexity change?