0
0
Swiftprogramming~5 mins

Closures as function parameters in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures as function parameters
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The closure task() is called inside a loop.
  • How many times: It runs exactly times times, once per loop iteration.
How Execution Grows With Input

As the times value grows, the number of times the closure runs grows the same way.

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

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means if you double the input size, the closure runs twice as many times.

Common Mistake

[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.

Interview Connect

Understanding how closures run inside loops helps you explain how your code scales and shows you can think about performance clearly.

Self-Check

"What if the closure itself contains a loop that runs n times? How would the time complexity change?"