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.

func doFileProcessing() {

defer {
// Close the file handle. Clear up unwanted resources. If networking API was used, close the network handle as well.
}

// Open file container, read file, store contents into collection. Update UI
}

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.

func doFileProcessing() {

defer {
// Close the file handle. Clear up unwanted resources. If networking API was used, close the network handle as well.
print("Third defer")
}

defer {
print("Second defer")
}

defer {
print("First defer")
}

// Open file container, read file, store contents into collection. Update UI
}

So above code will print following output,

Markup
First defer  
Second defer  
Third defer  

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.