(Swift) Defer Statement

Kenta Kodashima
3 min readJan 14, 2019

--

The image is created via https://imgflip.com/

The defer statement was first added back in Swift 2.0. This feature can be useful if you know how to use it properly. In this article, I will show you how defer works.

1. What is a defer statement?

According to Apple’s official Swift language guide, the defer statement is described as below.

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

In other words, the statements inside of the defer block are guaranteed to executed right before the function ends.

2. How it works

2.1 The basic execution orders

Basically, the code inside of the normal scope is executed first, and then the code inside of defer block is executed.

func example() {
defer {
print("First defer")
}
print("End of function")
}
example()/*
Prints:
"End of function"
"First defer"
*/

What’s going to happen if you add another defer to the example above.

func example() {
defer {
print("First defer")
}
defer {
print("Second defer")
}
print("End of function")
}
example()/*
Prints:
"End of function"
"Second defer"
"First defer"
*/

If a function has multiple defer statements inside of the scope, they are executed in the reverse order.

2.2 The function with ‘return’ statement

If defer statements are used in a function which returns something, the defer block is executed after the function returns. In this case, you can think of the defer statement as a completion handler because it is executed after the function returns and before the function ends.

class Counter {
var count = 0
func returnCurrentCountAndIncrement() -> Int {
defer {
count += 1
}
print(count) return count
}
}
let counter = Counter()
counter.returnCurrentCountAndIncrement() // Print "0"
counter.returnCurrentCountAndIncrement() // Print "1"
counter.returnCurrentCountAndIncrement() // Print "2"

In the example above, returnCurrentCountAndIncrement() prints and returns the current count of the Counter class, and then increment the count property after the function prints and returns.

3. Use cases

In Apple’s official documents, I found good use case examples.

The statements within the defer statement are executed no matter how program control is transferred. This means that a defer statement can be used, for example, to perform manual resource management such as closing file descriptors, and to perform actions that need to happen even if an error is thrown.

In the example below, the defer statement is called at the end of the function. Therefore, the file is guaranteed to be closed at the end.

func processFile(filename: String) throws {
if exists(filename) {
let file = open(filename)
defer {
close(file)
}
while let line = try file.readline() {
// Work with file such as write to another file
}
}
}

That’s everything for this article. Thank you for reading.

Reference:

Statements: Defer Statement — THE SWIFT PROGRAMMING LANGUAGE Swift 4.2:
https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_defer-statement

Error Handling: Specifying Cleanup Actions — THE SWIFT PROGRAMMING LANGUAGE Swift 4.2:
https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html

Swift Alley: Defer Statements:
https://medium.com/swiftcraft/swift-alley-defer-statements-b0286bdad496

--

--

Kenta Kodashima
Kenta Kodashima

Written by Kenta Kodashima

I'm a Software Engineer based in Vancouver. Personal Interests: Books, Philosophy, Piano, Movies, Music, Studio Ghibli.

No responses yet