Member-only story
The Defer Statement in Swift
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.