📖 Scenario: Imagine you are writing a small Swift program that opens a file, writes some data, and then closes the file. You want to make sure the file is always closed properly, even if something goes wrong while writing.
🎯 Goal: Build a Swift program that uses the defer statement to ensure the file is closed after writing, demonstrating how to clean up resources safely.
📋 What You'll Learn
Create a variable called fileOpen and set it to true to simulate an open file.
Create a variable called dataToWrite with the string "Hello, Swift!".
Use a defer block to set fileOpen to false to simulate closing the file.
Print messages to show when writing starts, the data being written, and when the file is closed.
💡 Why This Matters
🌍 Real World
In real apps, you often open files, network connections, or databases. Using <code>defer</code> helps you close these safely, avoiding bugs or crashes.
💼 Career
Understanding <code>defer</code> is important for Swift developers to write reliable and clean code, especially when managing resources.
Progress0 / 4 steps
1
Setup file status and data to write
Create a variable called fileOpen and set it to true. Then create a variable called dataToWrite and set it to the string "Hello, Swift!".
Swift
Hint
Use var to create variables and assign the exact values given.
2
Add defer block to close the file
Add a defer block that sets fileOpen to false to simulate closing the file.
Add print statements to show "Start writing data..." before writing, then print the dataToWrite variable.
Swift
Hint
Use print() to show messages and the data variable.
4
Print file closed status
After the previous code, print "File closed: false" before the defer block runs, and then print "File closed: true" after the defer block runs by printing the fileOpen variable.
Swift
Hint
Print the fileOpen variable after writing to show the file is still open before defer runs.
The defer block runs after the current scope ends, so the file closes after the prints.
Practice
(1/5)
1. What does the defer statement do in Swift?
easy
A. Skips the rest of the function
B. Runs code just before the function returns
C. Runs code immediately when the function starts
D. Runs code only if an error occurs
Solution
Step 1: Understand the purpose of defer
The defer statement 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 B
Quick Check:
defer runs code before function ends = C [OK]
Hint: Remember: defer runs code at function exit, not start [OK]
Common Mistakes:
Thinking defer runs immediately
Confusing defer with error handling
Assuming defer skips code
2. Which of the following is the correct syntax to use a defer statement in Swift?
easy
A. defer -> { print("Cleanup") }
B. defer: print("Cleanup")
C. defer() print("Cleanup")
D. defer { print("Cleanup") }
Solution
Step 1: Recall correct defer syntax
The defer statement 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 D
Quick Check:
defer uses braces {} for code block = D [OK]
Hint: defer always uses braces { } for its code block [OK]
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.