Lesson 019 – Defer

DeferWhen you are writing applications for mobile devices, being a good steward of resources is important. When you are through using objects or resources, you should release them so that the device can allocate the resources for other purposes. However, making sure you clean up resources every time you prepare to return can be difficult and result in a lot of copy/paste code.

Introduction

The defer keyword creates a stack of commands that are executed when the current scope (typically a method) ends. For those of you unfamiliar with a stack, think of it like a list of things. However, unlike a queue where first in line is the first out of line, a stack operates on a Last-In-First-Out (LIFO) model.

Think about a list that contains A B C D. In a queue, which is a First-In-First-Out (FIFO) model, that list would be unloaded as A B C D. However, if that list were a stack, it would be unloaded as D C B A. This makes sense in English terms, too. If you had a stack of Blu-Ray Disks, the first one you would have to move to get to the bottom would be the last one you piled on.

Defer by Example

Defer is written as a block of code like if…else or do…while. Let us first take a look at code that requires cleanup to happen in multiple places.

You’ll notice that this method can return in two different places, depending on the argument that is passed in. However, if we declare the method’s cleanup code with defer right at the beginning, it will execute automatically when the method is exited – regardless of where that occurs.

Now, if I call this method with 0, I get

If I call the method with 1, I get

This example only dealt with one defer block, though. As I mentioned at the beginning, you can add several defer blocks in your code. Typically, you want to add the defer block right after you declare the thing you need to clean up. Take a look at this method. I declare a method-level cleanup, a cleanup after dealing with the NSBundle, and a cleanup after messing with the NSDate. As an added bonus, those only get added if method execution gets that far, saving my cleanup code from having several if statements and null checks.

Now, if I call into that method passing in 1, 2 or 3, I get the following 3 results. Notice how the added defer blocks are executed in reverse order from how they were added.

Conclusion

You can – of course – write successful Swift applications without using defer. However, defer is one of those language features that will help you to write cleaner code that is easier to read and to maintain. It is always a good idea to declare variables near where you use them (don’t declare them all at the top just to “put them in a spot”). And by the same token, it is better to declare the cleanup at the same time you declare the variables. It is a best practice that will serve you well as you progress on your career.

Add Comment

Required fields are marked *. Your email address will not be published.