Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 146 ยท Error Handling

defer and Cleanup

Learn how Swift's defer statement runs cleanup code when a scope exits, in what order several defers run, how it works with throw and return, and its limits.

Many tasks follow the same shape: acquire something, use it, give it back. You open a file, read it, close it. You lock a resource, change it, unlock it. You print a header, do some work, print a footer. The trouble is the "give it back" step. If the function has three early returns and two places that can throw, you must remember to clean up in all five. Forget one and you leak a resource or leave a lock held forever.

Swift solves this with defer. A defer block is a piece of code you write now that Swift runs later, at the moment the current scope exits, no matter how it exits: reaching the end, return, break, continue or a thrown error. This lesson shows how it works, in which order several defer blocks run, how it pairs with throwing functions, and the few things it cannot do.

The basic idea

Put defer { ... } anywhere in a scope. The code inside is not executed at that line. It is remembered, and it runs when control leaves the scope.

Swift A defer block runs when the scope ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output order is start, working, still working, cleanup, after greet. The defer statement is written in the middle, but its body runs last, just before the function returns to its caller.

The point of writing it early is proximity: the cleanup sits right next to the code that needs it. You open a file and, on the next line, write the code that closes it. A reader sees the pair together, and you cannot forget the second half later.

defer runs on every exit path

The real power shows when a function has several ways out. The deferred block runs on all of them.

Swift defer with early returns and a thrown error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The "close connection" line appears for all three calls: a normal return, an early return and a thrown error. Without defer you would have to repeat the closing code before every return and before the throw. Add a fourth exit later and you would have to remember it again.

Write the defer immediately after the code that acquires the resource. Then it is in place before anything can fail, and every exit that follows is covered.

Several defers run in reverse order

A scope can contain more than one defer. They run in reverse order of how they were written: the last one first. This is "last in, first out", the same order you would use to unwind nested resources. If you opened A, then B, then C, you should close C, then B, then A.

Swift Multiple defers run last-in, first-out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The cleanup lines print as serve plate, wash pan, turn off stove: the reverse of the order in which the defer statements were reached. This matches the way a stack works, and it is almost always what you want, because later resources often depend on earlier ones.

An important detail: a defer is only registered if execution reaches it. If a function returns before the defer line, that block never runs, because it was never set up. That is another reason to place it right after the acquisition and before risky code.

Swift A defer that is never reached does not run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

For check(-5) the function returns before the defer line, so you see no cleanup message. For check(7) the defer is registered and then runs at the end.

Where deferred code finds its values

A defer block is ordinary code in the scope where it is written. It can read local variables, and it sees their value at the time it runs, not at the time you wrote it.

Swift defer sees the value at the end of the scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The deferred print shows final count: 7, not 0, because it reads count when the scope ends. That is exactly what you want for logging a summary or releasing a counter. If you want the value captured at the time of the defer statement instead, copy it into a constant first: let snapshot = count and use snapshot inside the block.

A realistic example: a resource with open and close

Here is a small class that pretends to be a file handle. It counts how many handles are open, so you can see whether code leaks them.

Swift Never leaking a handle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Every handle is closed, even for broken.txt, where read() throws. The last line prints handles still open: 0. (The nonisolated(unsafe) on the counter tells the Swift 6 compiler that you take responsibility for a global mutable value. It is fine in this single-threaded teaching program; real shared state should use an actor or a Mutex.)

defer in loops and blocks

defer is tied to the scope it is written in, not just to functions. Inside a loop body, it runs at the end of every iteration. Inside a plain do { } block, an if, or a guard, it runs when that block ends.

Swift defer inside a loop body and a do block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In round 2 the continue skips the rest of the body, but "round 2 ends" is still printed, because continue leaves the scope and defer runs on every exit. The do block shows that you can use defer to get cleanup for just a few lines, without making a new function.

What defer cannot do

The deferred block is for cleanup, and Swift enforces that it cannot change how the scope exits. You cannot return, break, continue or throw out of a defer. The compiler rejects it.

Swift Jumping out of a defer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports an error on the return inside the block: 'return' cannot transfer control out of a defer statement. This rule keeps the exit path of your function readable. If you could return from a defer, a late block could silently replace the real result.

A defer block also has no way to receive an error: try is allowed inside it only when you handle the error there with do/catch or try?. If your cleanup can fail (closing a file can fail, for instance), decide what to do with that failure inside the block. Often the right choice is to log it and move on, since the function is already leaving.

Swift Handling a failing cleanup inside defer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

defer is not a destructor

New Swift programmers sometimes confuse defer with deinit (see Memory Management with ARC). They solve different problems:

  • defer is tied to a scope: it runs when a block of code ends.
  • deinit is tied to the lifetime of a class instance: it runs when the last strong reference goes away.

Use defer for temporary acquire and release inside one function: locks, counters, indentation levels, temporary state. Use deinit for resources owned by an object over a long time. For a resource that must be closed explicitly at a known moment, offer a close() method and call it with defer.

Common uses and pitfalls

Typical good uses:

  • Unlock a lock after a critical section.
  • Restore a setting after changing it temporarily (such as a current directory or a flag).
  • Decrement a counter or hide a spinner.
  • Close a file handle or free memory obtained from a C API.

Pitfalls to avoid:

  • Placing defer too late. If an early return or throw happens above it, it never runs.
  • Putting a lot of logic in it. Keep the block short and focused on undoing what you did.
  • Relying on it for output ordering that others must read. A defer at the top of a long function still runs at the bottom; if the reader cannot see the link, add a short comment.
  • Assuming it captures values. It reads variables when it runs, not when it was written.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does the code inside a defer block run?

    defer registers the block and runs it when the enclosing scope ends: normal end, return, break, continue or throw.
  2. 2. A function contains defer { print("A") } and later defer { print("B") }. What is the order of the output when the function ends?

    Multiple defers run in reverse order, last in, first out, like unwinding a stack.
  3. 3. In which case does a defer block NOT run?

    A defer only takes effect once execution passes through it. After that it always runs on exit.
  4. 4. Why does the compiler reject defer { return 5 }?

    Swift forbids leaving a defer block with control-transfer statements so the real exit path of the function stays clear.
  5. 5. What is the best way to use defer when you acquire a resource?

    Writing defer right after the acquisition keeps the pair together and guarantees cleanup on every later exit.

Summary

  • defer { ... } schedules code that runs when the current scope exits: end of scope, return, break, continue or a thrown error.
  • Several defers in one scope run in reverse order, last in, first out.
  • A defer only applies if execution reaches it, so place it right after acquiring the resource.
  • Deferred code reads variables at the time it runs, not when it was written.
  • It works in loops, do blocks and if bodies, since it follows scopes, not just functions.
  • You cannot return, break, continue or throw out of a defer; handle failing cleanup inside it with do/catch.
  • defer cleans up a scope; deinit cleans up when a class instance dies.

Next: Assertions and Preconditions