Swift defer Statement
Here we will explain the defer statement in Swift.
Basics of the defer Statement in Swift
The defer statement in Swift allows you to specify code that will be executed when the current scope is exited.
It runs no matter how the scope is exited, making it useful for cleanup tasks in case of unexpected errors within the scope.
The syntax of a defer statement in Swift is as follows:
defer {
[statements]
}
Let’s look at an example using a defer statement:
func testFunction1() {
print("Statement 1")
defer {
print("Defer 1")
}
print("Statement 2")
}
testFunction1()
The output will be:
Statement 1
Statement 2
Defer 1
You can see that the print statements run in the order: Statement 1 → Statement 2 → Defer 1.
Variables Inside a defer Statement
The values of variables used inside a defer statement are those at the time the defer is executed.
Let’s assign a value to a variable named value and print it inside a defer block:
func testFunction2() {
var value = 1
print("Statement 1 - value: \(value)")
defer {
print("Defer 1 - value: \(value)")
}
value = 2
print("Statement 2 - value: \(value)")
}
testFunction2()
The output will be:
Statement 1 - value: 1
Statement 2 - value: 2
Defer 1 - value: 2
You can see that the value of value in the defer block is 2, not 1.
Multiple defer Statements
When there are multiple defer statements in a scope, they are executed in reverse order, meaning the one defined last runs first.
func testFunction3() {
print("Statement 1")
defer {
print("Defer 1")
}
defer {
print("Defer 2")
}
defer {
print("Defer 3")
}
print("Statement 2")
}
testFunction3()
The output is as follows:
Statement 1
Statement 2
Defer 3
Defer 2
Defer 1
The defer statements execute in the order 3 → 2 → 1.
Using defer with do Blocks
You can also use defer with do blocks to create a scope, and the defer block will execute when exiting that scope.
func testFunction4() {
print("Statement 1")
do {
print("Statement 2")
defer {
print("Defer 1")
}
print("Statement 3")
}
print("Statement 4")
}
testFunction4()
The output will be:
Statement 1
Statement 2
Statement 3
Defer 1
Statement 4
Here, Statement 1 runs first. Inside the do block, the prints run in the order: Statement 2 → Statement 3 → Defer 1. Then, after exiting the do scope, Statement 4 runs.
That wraps up our explanation of the defer statement in Swift.