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