0
0
Swiftprogramming~5 mins

Defer statement for cleanup in Swift

Choose your learning style9 modes available
Introduction

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.
Swift
func example() {
    defer {
        print("Cleanup done")
    }
    print("Doing work")
}
The defers run in reverse order, so it prints "Inside function", then "First defer", then "Second defer".
Swift
func multipleDefers() {
    defer { print("Second defer") }
    defer { print("First defer") }
    print("Inside function")
}
Sample Program

This simulates opening a file, reading data, and then closing the file automatically at the end using defer.

Swift
func readFile() {
    print("Open file")
    defer {
        print("Close file")
    }
    print("Read data")
}

readFile()
OutputSuccess
Important Notes

defer always runs when the function exits, even if there is an error or early return.

Use defer to keep cleanup code close to resource allocation for easier reading.

Summary

defer runs code just before a function ends.

It helps clean up resources safely and clearly.

Multiple defer statements run in reverse order.