How To Use The “defer” keyword In Swift

Updated 5 December 2018


Hi guys, today we will learn about How To Use The “defer” keyword. Before starting to code first we need to know about an “defer” keyword.
defer keyword was already introduced in Swift 2.0, the defer keyword provides a safe and easy way to handle this challenge by declaring a block that will be executed only when execution leaves the current scope.

->How does it work?

A defer statement is used for executing code just before transferring program control outside of the scope that the statement appears in.

->A common use case

The most common use case seen around is opening and closing a context within a scope, for example when handling access to files. A FileHandle requires to be closed once the access has been finished.
You can benefit from the defer statement to ensure you don’t forget to do this.

->Here we are taking the one problem for understanding the “defer” keyword use and how “defer” keyword is benfitial for swift robust coding.


we construct a path to the file (1). We then open the file for updating and obtain a handle to the opened file (2).
We then construct our data to write to the file (3), seek to the start of the file (4), write our data (5), and then close the file (6).
Relatively simple. The only real complication we might encounter is that we may fail to open the file (for example if it didn’t exist) in which case we throw an error and return. However, now imagine that instead of writing a simple string like Hello World to the file the function instead called another function (fetchData()) to get hold of the data it was going to write.
Also, imagine that that call required some intensive computation and could potentially result in an error being thrown (3):


-> Now The solution Above Problem we can easily solve by “defer” keyword.

The “defer” statement provides a clean way to handle these types of a situation by declaring a block of statements that will be executed when execution leaves the current scope.
It’s almost like pushing the statements within the defer statement onto a stack for later execution. We’ll revisit this analogy later. On top of this deferred execution,
the added bonus with the defer statement is that its block of statements are actually guaranteed to be executed regardless of how execution leaves the current scope.
This includes situations where we exit due to an error being thrown or because of statements such as a return or a break statement being executed.
As you can imagine, this makes the defer statement ideal for cleaning up previously created resources such as file descriptors (as in this example),
manually allocated memory or closing connections to a database. So this is all well and good, but what does the defer statement look like in practice?
The good news here is that the defer statement is actually super simple and has the following general form:
defer {
// Statements

As you can see, it’s just the defer keyword followed by a set of curly braces that enclose a set of Swift statements. These are the statements that will be executed when the current scope exits. With this in mind let’s tweak our example:

->Using Multiple defer Statements

Using multiple defer statements within a single scope is not a limitation per se, just something you should watch out for as the resulting execution may not be quite what you expect.
When multiple defer statements appear in the same scope, each defer statement is actually executed in a first-in-last-out (FILO) manner – i.e.
the set of statements associated with the first defer block that is encountered and pushed onto the stack are the last set of statements that are actually executed.
One way of thinking about it is to extend our analogy from earlier and think of each defer statement being a stack.
When the first defer statement is encountered it is pushed onto the stack. When the second defer statement is encountered it is also pushed onto the stack but on top of the first etc.
When execution then exits the current scope, each defer statement on the stack is then popped off the stack from the top of the stack.
This results in the defer statements being executed in the reverse order from which they were encountered.We can see this from a simplified example below:


By executing the defer blocks in this way Swift ensures that everything that was created prior to encountering the defer block such as constants or variables are still be in scope when the statements within the defer statement are executed.


So pls follow the above step and And if you have any issue or suggestion you can leave your message in the comment section I will try to solve this.

. . .

Leave a Comment

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

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home