Swift Defer Statement
A defer statement is a block of code that runs when the current scope is about to end. The block runs on every path that leaves the scope.
A defer runs before the caller continues
The greet function registers its defer and then prints its working line. The cleanup line prints after the return value is worked out and before the caller prints it.
func greet() -> String {
defer {
print("Cleanup")
}
print("Working")
return "Done"
}
let result = greet()
print(result)Two defers run in reverse order
The body line prints first because both defers wait for the scope to end. The defer written second then runs before the defer written first.
func run() {
defer {
print("First written")
}
defer {
print("Second written")
}
print("Body")
}
run()A defer inside a loop body
Each pass through the loop body is its own scope. The defer registered in a pass runs at the end of that same pass, before the next pass starts.
for number in 1...3 {
defer {
print("End \(number)")
}
print("Start \(number)")
}A defer runs on an early return
The check function returns early for a negative value. Its defer still runs before each return reaches the caller, so the leaving line prints twice.
func check(_ value: Int) -> String {
defer {
print("Leaving check")
}
if value < 0 {
return "Negative"
}
return "Positive"
}
print(check(-1))
print(check(5))Example
func process() -> Int {
defer {
print("Closing")
}
defer {
print("Saving")
}
print("Working")
return 3
}
let count = process()
print(count)Key points
- A defer block is registered when its line runs, but its code runs later.
- The deferred code runs when the enclosing scope is about to end.
- In a function, deferred code runs after the return value is worked out.
- The caller continues only after the deferred code has run.
- Two defer blocks in one scope run in reverse order, with the last one written running first.
- A defer inside a loop body runs at the end of that pass through the loop.
In this example, the process function registers two defers and then prints Working. The return value 3 is worked out next, and the two defers run in reverse order, printing Saving and then Closing. The caller prints the count 3 only after both defers have run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function writes defer A, then defer B, then prints Body and returns. In what order do the lines print?