0
0
Swiftprogramming~5 mins

Autoclosures (@autoclosure) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Autoclosures (@autoclosure)
O(n)
Understanding Time Complexity

We want to understand how using @autoclosure affects the time it takes for code to run.

Specifically, we ask: does wrapping expressions in autoclosures change how many steps the program takes as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

func logIfTrue(_ predicate: @autoclosure () -> Bool) {
    if predicate() {
        print("It's true!")
    }
}

logIfTrue(2 > 1)
logIfTrue(3 > 5)

This code uses an autoclosure to delay evaluating a condition until inside the function.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the autoclosure to evaluate the condition once per function call.
  • How many times: Once each time logIfTrue is called.
How Execution Grows With Input

Each call to logIfTrue evaluates the condition exactly once.

Input Size (n)Approx. Operations
1010 condition checks
100100 condition checks
10001000 condition checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with how many times the function is called.

Common Mistake

[X] Wrong: "Using @autoclosure makes the code run faster because it delays evaluation forever."

[OK] Correct: The condition still runs once when called inside the function, so the total work depends on how many times the function runs.

Interview Connect

Understanding how autoclosures affect execution helps you explain code behavior clearly and reason about performance in real projects.

Self-Check

What if we changed @autoclosure to a regular closure? How would the time complexity change?