Defer keyword in Swift
defer
is a new keyword indroduced in Swift 2.0. With this statement you can declare clean-up code, that is executed just before the current scope ends.
Defer is usually used to cleanup the code after execution. This might involve deallocating container, releasing memory or close the file or network handle. When put into the routine, code inside defer block is last to execute before routine exits. Routine in this case could refer to a function. Sometimes when function returns there are hanging threads, incomplete operation which needs to cleanup. Instead of having them scattered across function, we can group them together and put in the defer block. When function exits, cleanup code in the defer gets executed. For e.g.
In the above example, function doFileProcessing
will handle file operation. When function returns, instead of having to write file closing code anywhere in the routine, we have grouped it under defer which gets executed at very end.
This is equally true if you prematurely return from function before it reached an end. As soon as return is called, the defer
block gets executed before exiting the routine.
One of the most powerful features of defer is that you can stack up multiple deferred pieces of work, and Swift will ensure they all get executed.
So above code will print following output,
As it is clear defer
always follows reverse
order i.e. it is always the last statement to execute and it follows the order from bottom to top.
Note:
Your defer calls shouldn’t try to exit the current scope using something like a return call or throwing an error.