|

defer: Put Cleanup Next to Setup

Deferred cleanup, Molecules of Swift #011

A function that opens a file, acquires a lock, or temporarily changes application state takes on a responsibility: it must eventually undo that operation. Adding an early return or a throwing call can introduce another exit path. If cleanup is written separately at every exit, maintaining the function means maintaining all those copies as well.

Swift offers a different way to express that responsibility. With defer, we can place cleanup beside setup while leaving the rest of the function focused on its actual work. This Molecule explores when deferred code runs, how multiple cleanup operations interact, and where this small pattern stops being useful.

Register cleanup where the responsibility begins

Consider a simplified operation that reports when a session opens and closes. The messages represent resource management rather than an actual connection. Without defer, both paths need their own cleanup call.

func processWithoutDefer(valid: Bool) {
    print("Open")

    guard valid else {
        print("Rejected")
        print("Close")
        return
    }

    print("Processed")
    print("Close")
}

processWithoutDefer(valid: true)
processWithoutDefer(valid: false)
// Open
// Processed
// Close
// Open
// Rejected
// Close

The two calls produce different processing messages, but both must print Close. If we add another early return after Open, we must remember to close the session there too. Now move that responsibility next to the opening operation:

func process(valid: Bool) {
    print("Open")
    defer { print("Close") }

    guard valid else {
        print("Rejected")
        return
    }

    print("Processed")
}

process(valid: true)
process(valid: false)
// Open
// Processed
// Close
// Open
// Rejected
// Close

The first call reaches the end of the function. The second leaves through the guard’s early return. Both execute the deferred block before control returns to the caller. The output is unchanged, but the two cleanup calls have become one.

The important distinction is that reaching a defer statement registers work for later; it does not execute the body immediately. Placing it directly after acquisition makes the relationship visible without forcing the reader to inspect every exit path.

Errors do not require another cleanup branch

The same mechanism applies when a Swift error propagates out of a scope.

enum ProcessingError: Error {
    case invalid
}

func decode(valid: Bool) throws {
    print("Begin")
    defer { print("End") }

    guard valid else {
        throw ProcessingError.invalid
    }

    print("Decoded")
}

for valid in [true, false] {
    do {
        try decode(valid: valid)
    } catch {
        print("Caught")
    }
}
// Begin
// Decoded
// End
// Begin
// End
// Caught

On success, End follows Decoded. On failure, End appears before Caught because the function exits before the caller handles the error. The defer block neither catches nor suppresses the error; the caller still handles it.

Notice that Begin occurs before the defer statement. In a real acquisition that can throw, register cleanup after successful acquisition, not before it.

The boundary is a scope, not necessarily a function

A defer belongs to its enclosing lexical scope. That might be a function, an if body, a loop iteration, or an explicit do block.

func render() {
    defer { print("Finish render") }

    do {
        print("Push state")
        defer { print("Pop state") }
        print("Draw")
    }

    print("Present")
}

render()
// Push state
// Draw
// Pop state
// Present
// Finish render

Pop state runs when the do block ends, before Present. Finish render belongs to the outer function and runs later. An explicit do block is therefore useful when a temporary state or resource should be released before subsequent work in the same function.

Cleanup runs in reverse order

When several defer statements are reached in the same scope, Swift executes their bodies in reverse registration order.

func export() {
    print("Open destination")
    defer { print("Close destination") }

    print("Create writer")
    defer { print("Finish writer") }

    print("Write data")
}

export()
// Open destination
// Create writer
// Write data
// Finish writer
// Close destination

The writer finishes before the destination closes. This ordering matters when one resource depends on another: the dependent resource must finish while its dependency is still available. Register each cleanup beside its own setup rather than collecting unrelated cleanup operations at the bottom of the function.

Registration must actually be reached

A deferred block is not installed merely because its source code exists in a function.

func reserve(available: Bool) {
    guard available else {
        print("Unavailable")
        return
    }

    print("Reserved")
    defer { print("Released") }
    print("Use reservation")
}

reserve(available: false)
reserve(available: true)
// Unavailable
// Reserved
// Use reservation
// Released

The first call returns before registration, so it never prints Released. The second registers cleanup after Reserved and releases the reservation at scope exit. This is why cleanup belongs after the operation that establishes the responsibility.

Deferred code sees later changes

A defer body executes later, and reading a mutable local variable inside it can observe changes made after registration.

func measure() {
    var count = 0
    defer { print(count) }

    count = 3
}

measure()
// 3

The value is read when the deferred body runs, not when the statement is reached. If cleanup must refer to a particular resource identity, prefer a stable local constant rather than a mutable variable that may be reassigned before exit.

Where the pattern earns its place

Imagine a ticket pool shared by several synchronous callers. Reserving a ticket requires checking the remaining count and updating it as one protected operation. Foundation’s NSLock can protect that critical section.

import Foundation

final class TicketPool {
    private let lock = NSLock()
    private var remaining = 1

    func reserve() -> Bool {
        lock.lock()
        defer { lock.unlock() }

        guard remaining > 0 else { return false }
        remaining -= 1
        return true
    }
}

let pool = TicketPool()
print(pool.reserve()) // true
print(pool.reserve()) // false

The pool starts with one ticket. The first call returns true and reduces the remaining count to zero; the second returns false without changing the count. Both paths unlock before returning. If several callers share the same pool, the lock prevents their checks and updates from interleaving. The two calls shown here illustrate the success and failure paths; they are not a concurrent stress test.

When an API already provides scoped locking, such as withLock, prefer that form. The explicit lock and defer here make the acquisition and release visible. An NSLock must be unlocked on the thread that acquired it, so do not hold it across a suspension point.

The same pattern is useful for closing manually owned file descriptors or restoring temporary rendering state. It is unnecessary when an existing API already owns the cleanup, and it should not be used to hide a substantial operation whose failure the caller needs to handle.

Boundaries and experiments

A defer body cannot transfer control outside itself with return or a propagating throw. It is not a recovery mechanism for process termination, fatal errors, or crashes. Swift 6.3 and earlier do not allow an asynchronous call directly inside a defer body. Swift 6.4 introduces this capability through SE-0493: in an asynchronous context, a deferred body may use await, and scope exit waits for it to finish. A synchronous context still cannot do this. Cancellation is not automatically suppressed: cleanup APIs that observe task cancellation may still fail or stop early. Handle cleanup errors within the deferred body, or use an explicit completion path if the caller needs to receive those errors.

Try moving the Pop state defer from the do block in render to just before the do block, after the Finish render defer. Its cleanup will then run after Present, before Finish render. In export, try reversing the order of the two defer declarations while leaving setup unchanged: the cleanup messages reverse as well. These are deliberate experiments, not recommended changes to resource ownership.

The responsibility belongs beside the acquisition

The useful habit is not to put every final action in defer. It is to recognize a responsibility that begins now and must end when a scope exits. By expressing that pair locally, a function can gain new return paths without gaining another copy of the cleanup logic. Scope becomes an explicit part of the resource’s lifetime.

Sources
Next PostAssociated Values: Put Data Where It Belongs