0Pricing
Swift Academy · Lesson

How defer Works

Run code at scope exit regardless of path.

What defer Does

A defer block schedules code to run when the current scope is about to exit, no matter how it exits.

func demo() {
    defer { print("cleanup") }
    print("work")
}
demo()

Runs at Scope Exit

The deferred code runs after the rest of the scope finishes, just before control leaves it.

func greet() {
    defer { print("goodbye") }
    print("hello")
}
greet()

All lessons in this course

  1. How defer Works
  2. Multiple defer Blocks Ordering
  3. defer for Resource Cleanup
  4. defer with Errors and Early Returns
← Back to Swift Academy