0
0
Swiftprogramming~15 mins

Defer statement for cleanup in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Defer Statement for Cleanup in Swift
📖 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
Need a 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.
Swift
Need a hint?

Write defer { fileOpen = false } exactly to ensure cleanup.

3
Write data with print statements
Add print statements to show "Start writing data..." before writing, then print the dataToWrite variable.
Swift
Need a 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
Need a 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.