Asynchronous cleanup
Async calls in defer
Swift 6.4 allows a defer block to call asynchronous functions, making it easier to guarantee async cleanup when leaving a scope.
Before Swift 6.4
In Swift 6.3 and earlier, using await inside a defer block produced a compiler error:
func performOperation() async {
defer {
await flush() // Error: 'async' call cannot occur in a defer body
}
// Perform work...
}
Swift 6.4
An async function can now suspend while running its deferred cleanup:
func performOperation() async {
defer {
await flush()
}
// Perform work...
}
The deferred block still runs when its surrounding scope exits, but it can now await asynchronous cleanup before the function returns.