Defer statement in swift is executed just before the control exits the scope in which defer is defined. Swift’s official document states
Swift.org
defer
statement for running cleanup actions just before the current scope exits.
A few important points regarding swift defer statement are
- swift defer statement is executed just before the control exits the scope in which differ is defined
- swift defer statement can be used to cleanup or log diffrent exit points of your function
- Only those defer statement which are defined above a return point in function are excuted. We will see this in example
- swift defer statement are excuted in reverse order of there occurance
Swift defer statement in action
In the following function, we have implemented multiple defer statements and a conditional return. We will execute the with return condition set to true and return condition set to false. The function is given below. I would also request you to try it in playground
class A { func tick( endFlow:Bool) { print("Function called") defer { print("Differ 1") } defer { print("Differ 2") } defer { print("Differ 3") } if endFlow { // return condition below 3rd defer return } defer { print("Differ 4") } defer { print("Differ 5") } print("Second statement executed") } } A().tick(endFlow: false) // return condition will not execute
In the example above we have implemented 5 defer statements and we have a return point that returns if the endFlow
param is true. We will execute this function with both endFlow = true
and endFlow = false
When endFlow
is false
Function called Second statement executed Differ 5 Differ 4 Differ 3 Differ 2 Differ 1
If you see the log you will observe
- that first the two print statement are executed in the order which they occour
- defer statement are executed in the reverse order of the occurence i.e defer 5 is executed first and defer 1 is executed last
When endFlow
is true
But when we set endFlow = true then something interesting happens
Function called Differ 3 Differ 2 Differ 1
- Only those swift defer statement which are abe return are executed
- Defer statement are still executed in reverse order
This helps us understand how to place our defer statements when we have multiple if le or guard statements that might return. Hope this helps!!!