The Swift `defer` keyword executes code just before leaving a scope, making it useful for cleanup tasks like closing file handles or ensuring completion callbacks are always called. Multiple defer blocks execute in reverse order. Swift 6.4 (SE-0493) adds support for `await` inside `defer` blocks when the surrounding context is async, allowing asynchronous cleanup without unstructured Tasks. Key rules: async defer only works in async contexts, blocks still run in reverse order, cleanup is awaited before scope exit, and task cancellation is still observable inside defer.
Table of contents
How does it work?Order of execution with multiple defer statementsA common use caseAwaiting asynchronous cleanup with deferEnsuring resultsA few rules to rememberFrequently Asked Questions around defer800 Impressions