Execution Order of Multiple Defer Blocks
February 16, 2024
I rarely need to use defer blocks and mostly it is for ending signpost intervals. I checked the possible situation of having multiple and in which order they are executed.
I will save you the talk and show you this simple example code instead:
import Foundation
struct MyType {
func myFunc() {
defer {
print("Declared first!")
}
defer {
print("Declared second!")
}
print("myFunc!")
}
}
let myValue = MyType()
myValue.myFunc()
This code will print:
myFunc!
Declared second!
Declared first!
I am happy to see this!
This means, that defer
blocks defined first to end signpost intervals are safe to be executed at last.