The Defer Statement in Swift

The Defer Statement in Swift
⏱ Reading Time: 3 mins

There are a few small things in Swift that can make a developer’s life much easier, and the coding process more efficient. One of them is the defer statement, which usually leads to writing shorter and simpler code when used. Before getting to know how to use defer, it’s necessary initially to understand its purpose. So, let’s get started with that.

What defer is all about

To get your head around the defer statement, begin by thinking of a party. A party where people have fun, have drinks, talk to each other, and eventually leave when the party’s finished. However, when that happens, there is always someone left behind to do the boring work; to clean up, throw the garbage, and bring the party place back to its original shape.

In this analogy, the defer statement is the guy who’s left behind responsible to do the clean up. The place where the party takes place is a certain scope, usually a function or a method. And the people who participate in the party and have fun are of course the various tasks and actions implemented in the scope.

With that picture in mind, you can now realize that the defer statement is the last thing executed within a block of code. It’s the place to perform finishing tasks, such as emptying temporary arrays, closing files and releasing previously allocated resources.

What makes defer actually interesting and useful, is the fact that it allows to write clean up code just once. Regardless of how many paths code execution may follow in a function or another block of code, defer takes away the need to perform finishing actions at the end of each path; that means that we avoid to repeat code multiple times, and we eventually end up with shorter -and smarter- implementations.

Understanding defer through examples

Consider the following dummy function:

Defer statement is usually written at the beginning of the scope, and after any initialization or resources we may allocate. Remember, however, that even though the defer statement is implemented first in the previous example, it will be the last one executed. Running the above will print the following:

Moving on to a different example, see the next fake code snippet:

At the beginning of the function we open a file, and load some content with arbitrary length into the content array. Both are resources we need locally in the function in order to make it achieve its purpose. Those have to be released when they are no longer needed, and we do that in the defer statement right next.

Notice that we also have a guard statement which leads to premature exit from the function if the condition is not met. Otherwise, the function is executed normally. If we had omitted defer, then we would have to repeat its contained statements twice; both in the else clause of the guard statement, and right before the end of the function. And even more than just twice, in case we had more guard statements, or other code that would cause to return from the method.

At this point, it’s necessary to underline a fact; defer statement should not contain any code that would transfer control out of the scope where it is defined. That means that we should avoid having statements like return or break in it, as well as to throw any errors.

Going to another fact, a code block may contain more than one defer statements. It’s important however to remember that they are executed in the opposite order they are written; the first defer statement is executed last. The following example clarifies that:

Printed values are displayed like so:

Conclusion

This is pretty much everything you need to know about the defer statement in Swift. In the few previous examples presented above, the block of code containing the defer statements was a function. However, other blocks can contain defer as well, such as for loops or do statements. In any case, it’s not difficult to understand how defer works, and if you had not been using it in your implementations, consider start doing so.

Thank you for reading, enjoy coding! 🙏

If you found this post useful then please consider sharing it! Also, subscribe to my newsletter in order to be notified about everything new published here directly in your inbox, and follow me on Twitter, on YouTube, on Medium and other social media.

👉 Wanna say thanks or support me?

Buy Me a Coffee!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.