The defer Statement
defer is a promise to do something right before leaving the current block of code, no matter how you leave it.
In this page:
Basic defer Usage
A defer block is written where cleanup logic conceptually belongs, but Swift delays actually running it until the function is about to exit.
Example: Basic defer Usage
func processFile() {
print("Opening file")
defer {
print("Closing file")
}
print("Processing file")
}
processFile()
Login to try C/C++/Java/PHP code in the editor
Multiple defer Blocks Run in Reverse Order
When a scope has several defer blocks, they execute in the reverse order they were written, like a stack.
Example: Multiple defer Blocks Run in Reverse Order
func demo() {
defer { print("First defer (runs last)") }
defer { print("Second defer (runs first)") }
print("Function body")
}
demo()
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming
deferruns immediately where it's written; it actually always runs at the very end of the enclosing scope. - Writing multiple
deferblocks and expecting them to run in the order written; they actually run in reverse order, last-in-first-out. - Using
deferfor logic that must run conditionally only on success;deferalways runs regardless of whether the scope exits normally or via a thrown error.
Chapter Summary
defer { }schedules code to run just before the current scope exits, regardless of how it exits.- Multiple
deferblocks run in reverse (last-in-first-out) order. deferis commonly used for cleanup, like closing a resource, that must always happen.deferruns whether the scope exits normally, viareturn, or via a thrown error.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: