Closures as function parameters in Swift - Time & Space Complexity
When we use closures as function parameters, we want to know how the time to run the code changes as the input grows.
We ask: How many times does the closure run as input size increases?
Analyze the time complexity of the following code snippet.
func repeatTask(times: Int, task: () -> Void) {
for _ in 0..
This code runs a closure called task a certain number of times given by times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The closure
task()is called inside a loop. - How many times: It runs exactly
timestimes, once per loop iteration.
As the times value grows, the number of times the closure runs grows the same way.
| Input Size (times) | Approx. Operations (closure calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means if you double the input size, the closure runs twice as many times.
[X] Wrong: "The closure runs only once no matter the input size."
[OK] Correct: The closure is inside a loop that runs times times, so it runs as many times as the input number.
Understanding how closures run inside loops helps you explain how your code scales and shows you can think about performance clearly.
"What if the closure itself contains a loop that runs n times? How would the time complexity change?"