When using a defer-statement, make sure the code remains readable and the execution order remains clear. For example, the following use of the defer-statement makes the execution order and the function of the code hard to comprehend.
When to use a defer statement
A defer statement consists of a block of code, which will be executed when a function returns and should be used for cleanup.
As Swift's guard statements encourage a style of early return, many possible paths for a return may exist. A defer statement provides cleanup code, which then does not need to be repeated every time.
It can also save time during debugging and profiling, as memory leaks and unused open resources due to forgotten cleanup can be avoided.
It can be used to deallocate a buffer at the end of a function:
It can also be used to close resources at the end of a function:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0