Defer statement for cleanup in Swift - Time & Space Complexity
We want to understand how using a defer statement affects the time it takes for a program to run.
Specifically, does adding cleanup code with defer change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
func processItems(_ items: [Int]) {
for item in items {
defer {
print("Cleanup for \(item)")
}
print(item)
}
}
This code prints each item in a list and then uses defer to print a cleanup message after each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for every item in the list.
Each item causes two print actions: one normal and one deferred cleanup.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 prints |
| 100 | 200 prints |
| 1000 | 2000 prints |
Pattern observation: The total work doubles but still grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items, even with defer cleanup.
[X] Wrong: "Defer adds extra loops or makes the program slower in a way that changes the overall time complexity."
[OK] Correct: Defer only adds a small fixed action after each loop iteration, so it grows with the loop and does not add nested or repeated loops.
Understanding how defer affects time helps you explain code cleanup clearly and shows you can think about performance even in simple-looking code.
What if the defer block contained a loop over all items instead of just a print? How would the time complexity change?
Practice
defer statement do in Swift?Solution
Step 1: Understand the purpose of
Thedeferdeferstatement schedules code to run at the end of the current function, just before it returns.Step 2: Compare options with this behavior
Only Runs code just before the function returns matches this behavior exactly; others describe different timings or conditions.Final Answer:
Runs code just before the function returns -> Option BQuick Check:
defer runs code before function ends = C [OK]
- Thinking defer runs immediately
- Confusing defer with error handling
- Assuming defer skips code
defer statement in Swift?Solution
Step 1: Recall correct
Thedefersyntaxdeferstatement uses the keyword followed by a block in curly braces:defer { ... }.Step 2: Check each option
Only defer { print("Cleanup") } matches the correct syntax. Others use invalid punctuation or structure.Final Answer:
defer { print("Cleanup") } -> Option DQuick Check:
defer uses braces {} for code block = D [OK]
- Using parentheses instead of braces
- Adding colons after defer
- Using arrow symbols incorrectly
func test() {
defer { print("First") }
defer { print("Second") }
print("Inside")
}
test()Solution
Step 1: Understand defer execution order
Multipledeferstatements run in reverse order of appearance when the function ends.Step 2: Trace the output
"Inside" prints first. Then the last defer prints "Second", then the first defer prints "First".Final Answer:
Inside Second First -> Option CQuick Check:
defer runs last-in-first-out = A [OK]
- Assuming defers run in order added
- Thinking defer runs immediately
- Mixing print order
defer:func cleanup() {
defer print("Done")
print("Working")
}Solution
Step 1: Check defer syntax
Thedeferstatement requires a code block enclosed in braces {}.Step 2: Analyze the given code
The code usesdefer print("Done")without braces, which is invalid syntax.Final Answer:
Missing braces {} after defer -> Option AQuick Check:
defer needs braces {} for code block = B [OK]
- Omitting braces for defer block
- Thinking defer can take single statement without braces
- Assuming defer must be last line
defer for cleanup in Swift?Solution
Step 1: Understand defer for cleanup
defer ensures cleanup code runs at function end, even if errors happen.Step 2: Apply defer after resource acquisition
Placedefer { close file }immediately after opening the file to guarantee closure.Final Answer:
Open file, write data, then use defer { close file } immediately after opening -> Option AQuick Check:
defer after open ensures cleanup always runs = A [OK]
- Placing defer after writing data
- Skipping defer on errors
- Closing file manually risking leaks
Ready to prove it?
Pass the test and this pattern moves unknown
