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:
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:
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 or to clean up values that are no longer needed. Let's look at an example of...