Typically, when we call a function, control passes from the call site to the function, 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, then 3:
Figure 3.2 – print statement
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 – defer statement
In this recipe, we will explore how to use defer, and when it can be helpful.