Swift 2.0: defer

defer is another new keyword in Swift. With this statement you can declare clean-up code, that is executed just before the current scope ends. For example, this scope can be a function or a loop.

Let’s take a look at an example:

If you want to run some clean-up code just before the function returns, you would insert them at two positions. And this is just a simple example.

But with defer you need to declare the clean-up code only once:

If you call this function with an argument of 3, the output will be

You can place the defer  statement at any position of the current scope, but it is considered as good practice to place it at the beginning of the current scope. It is also possible to have more than one  defer block in the current scope. They are executed then in reverse order.

The  defer block is also executed if the current scope ends due to a thrown error:


With  defer  you can declare clean-up code that is executed if the current scope ends. This improves the readability of your code and the code quality overall.

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.