Use Swift 6.4 Async Defer For Reliable Cleanup

A function acquires a resource, performs some asynchronous work, and needs an asynchronous release. An older workaround puts a new Task inside defer. That launches cleanup, but the function can return before cleanup finishes.

Swift 6.4 gives that code a better shape: await can appear directly inside defer in an asynchronous context. SE-0493 specifies that the deferred work is awaited at scope exit. The caller can now rely on the cleanup attempt finishing before control returns.

Separate cleanup ordering from cancellation

Awaiting cleanup does not automatically make it ignore cancellation. If the task was cancelled, a release implementation that checks cancellation can still stop early.

The related task cancellation shield proposal adds withTaskCancellationShield. It temporarily changes cancellation observation inside a small scope. It does not erase the surrounding task’s cancelled state.

Here is a helper for a lease whose release should be attempted even when the operation is cancelled:

import Foundation

protocol AsyncLease: Sendable {
    func release() async throws
}

@available(iOS 27.0, macOS 27.0, *)
func usingLease<Value: Sendable>(
    _ lease: some AsyncLease,
    cleanupFailed: @Sendable (any Error) async -> Void,
    operation: @Sendable () async throws -> Value
) async throws -> Value {
    defer {
        await withTaskCancellationShield {
            do { try await lease.release() } catch { await cleanupFailed(error) }
        }
    }
    return try await operation()
}

The lease is already acquired when this helper begins. Its ownership contract is that this scope will attempt to release it once. The protocol keeps the example independent of a particular connection pool or file service.

The annotation is deliberate. With the installed Xcode 27 SDK, the cancellation-shield API requires iOS 27 or macOS 27. The language feature and the runtime API have different availability questions. An app supporting older systems needs an availability branch and its existing compatible cleanup path; upgrading the compiler alone does not make every standard-library API available on every deployment target.

Decide what a cleanup error means

This helper preserves the operation’s result and reports release failures through a separate callback. That is a policy choice, suitable only when the caller has a meaningful way to record or recover a failed release.

It would be wrong for a “commit document” API if a failed final flush means the document was never saved. In that case, make the required finalization part of the throwing success path and design failure handling explicitly. Do not rename a failed commit “cleanup” and then hide its error.

A defer body cannot simply throw a new error out over the operation’s result. Catch errors where you can choose what they mean. Avoid a casual try? that loses the only evidence that a remote lease or local resource remained open.

Keep the shield small

The shield wraps release and its failure reporting. It does not wrap the user’s entire export, network download, or search. The user should still be able to cancel the work they asked to stop.

A shield also does not repair network failure, grant background execution time, or keep a killed process alive. If release talks to a server, give that request a bounded policy and a durable recovery path when needed. Waiting indefinitely for cleanup would turn cancellation into a hung operation.

Review timeout implementations carefully. A timeout that depends on inherited task cancellation has different behavior inside a shield. Use the underlying operation’s supported deadline or timeout mechanism, and test it instead of assuming an outer cancelled task will stop the cleanup.

Remember the suspension at scope exit

The new await is easy to overlook because the main body might end with a simple return. That return now waits for asynchronous cleanup.

For actor-owned state, a cleanup call that suspends can allow other work on the actor to run. Capture the resource identity needed for cleanup before suspension, and avoid treating a mutable “current resource” property as if it still referred to the same operation afterward.

Our stale actor-cache example demonstrates the broader rule: actor isolation protects synchronous regions, while identities and state checks protect decisions across suspension points.

Test what the caller observes

A useful fixture cancels its own task inside the operation, throws cancellation, and records whether release observed cancellation. After the helper exits, assert that release completed and that the surrounding task is still cancelled.

Also make release fail and verify that the failure callback runs before the helper returns its chosen result. These checks distinguish awaited cleanup from a fire-and-forget task that merely happens to run quickly on your machine.

September 2026 verification: the executable passed on macOS 27 with Swift 6.4: cleanup completed before the caller continued, release observed the shielded state, the caller retained cancellation afterward, and a release error reached the reporting callback. The availability-annotated sample also type-checks with an iOS 17 deployment target against the iOS 27 SDK; callers must still honor the iOS 27 availability boundary.

Async defer makes resource ownership easier to express. The remaining design work is deciding which cleanup must survive cancellation, how long it may take, and what the app does when the cleanup itself fails.