Autoclosures (@autoclosure) in Swift - Time & Space 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?
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 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
logIfTrueis called.
Each call to logIfTrue evaluates the condition exactly once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 condition checks |
| 100 | 100 condition checks |
| 1000 | 1000 condition checks |
Pattern observation: The number of operations grows directly with the number of calls.
Time Complexity: O(n)
This means the time grows linearly with how many times the function is called.
[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.
Understanding how autoclosures affect execution helps you explain code behavior clearly and reason about performance in real projects.
What if we changed @autoclosure to a regular closure? How would the time complexity change?