← Back to Swift Course | Chapter 11: Error Handling | Lesson 5 of 6

The defer Statement

defer is a promise to do something right before leaving the current block of code, no matter how you leave it.

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

markup
func processFile() {
    print("Opening file")
    defer {
        print("Closing file")
    }
    print("Processing file")
}
processFile()

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

markup
func demo() {
    defer { print("First defer (runs last)") }
    defer { print("Second defer (runs first)") }
    print("Function body")
}
demo()
Common Mistakes
  1. Assuming defer runs immediately where it's written; it actually always runs at the very end of the enclosing scope.
  2. Writing multiple defer blocks and expecting them to run in the order written; they actually run in reverse order, last-in-first-out.
  3. Using defer for logic that must run conditionally only on success; defer always 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 defer blocks run in reverse (last-in-first-out) order.
  • defer is commonly used for cleanup, like closing a resource, that must always happen.
  • defer runs whether the scope exits normally, via return, or via a thrown error.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.