---
title: "Defer in Swift explained with Code Examples"
url: https://daily.dev/posts/defer-in-swift-explained-with-code-examples-h9vthjklz
source_url: https://www.avanderlee.com/swift/defer-usage-swift
type: article
source: "SwiftLee"
published: 2026-07-06T12:53:41.066Z
updated: 2026-07-06T12:54:06.987Z
tags: ["ios", "swift"]
reading_time: 6
upvotes: 1
comments: 0
language: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Defer in Swift explained with Code Examples

**[SwiftLee](https://daily.dev/sources/avanderlee)** · 6 min read · 1 upvotes · 0 comments

## Summary

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.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://www.avanderlee.com/swift/defer-usage-swift>

## Similar posts on daily.dev

- [Swift Defer. Clean up before you leave.](https://daily.dev/posts/swift-defer-clean-up-before-you-leave--uaf4q4k9s) · Swift with Majid · 0 upvotes · 0 comments
- [Defer available in gcc and clang](https://daily.dev/posts/defer-available-in-gcc-and-clang-2as4i32ce) · Lobsters · 8 upvotes · 1 comments

---

Tags: [#ios](https://daily.dev/tags/ios), [#swift](https://daily.dev/tags/swift)

[View this post on daily.dev](https://daily.dev/posts/defer-in-swift-explained-with-code-examples-h9vthjklz)
