The defer statement helps you run some code right before a function ends. It is useful to clean up things like closing files or freeing resources, no matter how the function finishes.
When you open a file and want to make sure it closes before leaving the function.
When you allocate memory or resources and want to release them safely at the end.
When you want to run some cleanup code even if an error happens or the function returns early.
When you want to keep your cleanup code in one place at the end of a function for clarity.
Syntax
Swift
defer {
// code to run later
}
The code inside defer runs just before the function returns.
You can have multiple defer statements; they run in reverse order.
Examples
This prints "Doing work" first, then "Cleanup done" when the function ends.
The defer statement requires a code block enclosed in braces {}.
Step 2: Analyze the given code
The code uses defer print("Done") without braces, which is invalid syntax.
Final Answer:
Missing braces {} after defer -> Option A
Quick Check:
defer needs braces {} for code block = B [OK]
Hint: Always use braces {} after defer keyword [OK]
Common Mistakes:
Omitting braces for defer block
Thinking defer can take single statement without braces
Assuming defer must be last line
5. You want to open a file, write data, and ensure the file is always closed even if an error occurs. Which is the best way to use defer for cleanup in Swift?
hard
A. Open file, write data, then use defer { close file } immediately after opening
B. Write data, then open file, then defer { close file }
C. Use defer { close file } only if no error occurs
D. Close file manually without defer after writing
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
Place defer { 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 A
Quick Check:
defer after open ensures cleanup always runs = A [OK]
Hint: Place defer right after resource acquisition for safe cleanup [OK]
Common Mistakes:
Placing defer after writing data
Skipping defer on errors
Closing file manually risking leaks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.