The defer statement

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does f() print?

func f() {
    defer { print("1") }
    defer { print("2") }
    print("3")
}
f()
Options
Hint 1 of 1

Defers behave like a stack.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: C 3 2 1

Correct. The body runs, then the defers run in reverse order.

Why not the others?
  • A 1 2 3. Deferred blocks wait until the scope exits.
  • B 3 1 2. Defers run last-in, first-out.
  • D 3. Both defers run when the function returns.

30-second answer

defer schedules code to run when the current scope exits, however it exits: return, throw or falling off the end. Multiple defers run in reverse order of declaration. It keeps cleanup next to setup, for example unlocking a lock or resetting a loading flag.

Practise saying it · 30 s. No recording, just a timer

Explain defer.

Say your answer out loud, then check which of these points you covered:

  • Runs when scope exits
  • Reverse order
  • Cleanup next to setup

Deep dive

defer runs at the end of its scope, not the function, if declared inside an if or a loop.

You can't return or throw from inside a defer block.

Combine with isLoading = true; defer { isLoading = false }.

Defers run after the return value is computed, so they can't change what was already returned.

Common mistakes

  • Declaring defer after an early return (it never registers).
  • Expecting defers to run in declaration order.

Senior take & follow-ups

Seniors use defer for paired setup and cleanup and know the ordering rule.

Follow-up questions

Think of your answer first, then open the hint.

  1. Does defer run if the function throws?

    Show hint

    Yes.

  2. Does a defer inside a loop run once per iteration?

    Show hint

    Yes, at the end of each iteration.

Suggest a fix if something here is wrong or out of date.