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?
Practice
@autoclosure attribute do in Swift?Solution
Step 1: Understand the purpose of @autoclosure
@autoclosure automatically wraps an expression passed as an argument into a closure, delaying its execution until called.Step 2: Compare with other options
Options B, C, and D describe behaviors unrelated to @autoclosure's purpose.Final Answer:
Automatically wraps an expression into a closure to delay its execution -> Option CQuick Check:
@autoclosure delays execution = A [OK]
- Thinking @autoclosure runs code immediately
- Confusing @autoclosure with normal closures
- Assuming it changes closure syntax
@autoclosure in Swift?Solution
Step 1: Recall correct syntax for @autoclosure
The correct syntax places @autoclosure before the closure type:@autoclosure () -> Bool.Step 2: Analyze each option
func check(_ condition: @autoclosure () -> Bool) { } matches the correct syntax. Options A, B, and C misuse the attribute placement or type declaration.Final Answer:
func check(_ condition: @autoclosure () -> Bool) { } -> Option AQuick Check:
@autoclosure syntax = func check(_ condition: @autoclosure () -> Bool) { } [OK]
- Placing @autoclosure after the type
- Using @autoclosure on non-closure types
- Omitting the closure arrow syntax
func logIfTrue(_ predicate: @autoclosure () -> Bool) {
if predicate() {
print("True")
} else {
print("False")
}
}
logIfTrue(3 > 5)Solution
Step 1: Understand the function behavior
The function takes a condition as an autoclosure and calls it inside the if statement.Step 2: Evaluate the passed expression
The expression3 > 5is false, sopredicate()returns false, triggering the else branch.Final Answer:
False -> Option DQuick Check:
3 > 5 is false, so output = False [OK]
- Assuming autoclosure runs immediately before function call
- Confusing true/false logic
- Expecting compile errors due to autoclosure
@autoclosure:func execute(_ action: @autoclosure () -> Void) {
action
}
execute(print("Hello"))Solution
Step 1: Check how the closure is called inside the function
The parameteractionis a closure and must be called with parentheses:action().Step 2: Identify the error
The code usesactionwithout parentheses, so the closure is not executed, causing no output.Final Answer:
Missing parentheses to call the closure inside the function -> Option AQuick Check:
Closure must be called with () = Missing parentheses to call the closure inside the function [OK]
- Forgetting to call the closure with parentheses
- Thinking @autoclosure forbids Void closures
- Assuming print can't be autoclosure
@autoclosure to log messages only when needed:func log(_ message: @autoclosure () -> String, onlyIf condition: Bool) {
if condition {
print(message())
}
}
log("Debug info", onlyIf: false)What is the main benefit of using
@autoclosure here?Solution
Step 1: Understand how @autoclosure delays evaluation
The message string expression is wrapped in a closure and only evaluated whenmessage()is called.Step 2: Analyze the condition effect
Sinceconditionis false,message()is never called, so the string is not constructed, saving computation.Final Answer:
The message string is constructed only if the condition is true, saving resources -> Option BQuick Check:
@autoclosure delays message creation = The message string is constructed only if the condition is true, saving resources [OK]
- Thinking message is always created regardless of condition
- Assuming autoclosure prints automatically
- Confusing condition with message parameter
Ready to prove it?
Pass the test and this pattern moves unknown
