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:
Syntax
func functionName() {
defer {
// cleanup: runs when the scope exits
}
// main work
}
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
// Define the function `processFile` with no parameters
func processFile() {
// Print "Opening file" to the console
print("Opening file")
defer {
// Print "Closing file" to the console
print("Closing file")
}
// Print "Processing file" to the console
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
// Define the function `demo` with no parameters
func demo() {
defer { print("First defer (runs last)") }
defer { print("Second defer (runs first)") }
// Print "Function body" to the console
print("Function body")
}
demo()
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: