Doing it later with defer
Typically, when we call a function, control passes from the call site to the function, and then the statements within the function are executed sequentially until either the end of the function or until a return statement. Control then returns to the call site.
In the following diagram, the print statements are executed in the order 1, 2, and 3:
Figure 3.2 – The print statements
Sometimes, it can be useful to execute some code after the function has returned, but before control has been returned to the call site. This is the purpose of Swift’s defer
statement. In the following example, step 3 is executed after step 2, even though it is defined above it:
Figure 3.3 – The defer statement
In this recipe, we will explore how to use defer
and when it can be helpful.
Getting ready
A defer
statement can be useful to change the state once a function’s execution is complete...