Member-only story

The Defer Keyword in Swift

Playing around in Swift

--

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

Terminology:

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

This technical example shows how `defer` can be used and uses an asynchronous block to hammer home the point. Don’t worry too much about the logic of using `defer` in this case, this example is simply to show the nuts and bolts of using defer.

Let’s dive in!

final class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
var i: Item? = Item()
i = nil
print(i)
}
}

class Item {
init() {
print("called init")
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
defer { print("Dispatch 2") }
print("dispatch 3")
}
)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
print("Dispatch 1")
}
)
print("Dispatch 4")
}

deinit {
print("deinit called")
}
}

What is happening is that an instance of Item is created and then set to nil. This triggers the deinit

--

--

No responses yet