The Defer Keyword in Swift

Playing around in Swift

Steven Curtis
4 min readMay 2, 2024
Photo by Romain V on Unsplash

The reason for this article is that defer is often useful, but seldom used (in my experience) where it could make things much easier for programmers using swift.

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 15.0, and Swift 5.9


defer: A statement in Swift that schedules a block of code to execute just before exiting the current scope, ensuring resource cleanup and final actions are reliably performed

The defer statement

The defer statement in Swift allows developers to declare a block of code that will be executed in the future, specifically just before the current scope (such as a function, method, or loop block) exits. This helps to ensure that cleanup tasks are performed even if an error interrupts the happy path execution flow.

Not only that. Using defer can enhance readability and maintainability of code — specific situations where defer is useful include dealing with files, database connections, or any system resources that require explicit release or closure.

A simple example