What if you could guarantee cleanup code runs perfectly every time, no matter what?
Why Defer statement for cleanup in Swift? - Purpose & Use Cases
Imagine you open a file to read data, then you do many steps like processing and checking errors. You must remember to close the file at the end, no matter what happens. If you forget or an error occurs early, the file stays open and causes problems.
Manually closing resources like files or network connections is tricky. You have to put close commands everywhere, after every possible error or exit point. This is slow, easy to forget, and leads to bugs like memory leaks or locked files.
The defer statement in Swift lets you write cleanup code once, right after opening the resource. Swift guarantees this code runs last, even if errors happen or you return early. This keeps your code clean and safe.
let file = openFile() if error { closeFile(file); return } processFile(file) closeFile(file)
let file = openFile()
defer { closeFile(file) }
if error { return }
processFile(file)It makes your programs safer and easier to read by ensuring cleanup always happens without repeating code.
When downloading a photo from the internet, you open a connection. Using defer, you ensure the connection closes even if the download fails halfway.
Manual cleanup is error-prone and repetitive.
defer runs cleanup code automatically at the end.
This keeps your code simple, safe, and bug-free.
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
