The #swift “defer” statement is useful when we need certain tasks to be performed right before exiting the current scope

It ensures the execution of these tasks, regardless of how the scope is exited, whether through normal flow, return, or an exception.

The defer keyword can be defined only inside scopes, such as functions or do-catch blocks.

We can have many defers, and if there is more than one, they will be executed in reverse order (the last defined defer will be executed first).


The defer statement remains effective even in scenarios where errors are thrown and it ensures that the specified code will be executed just before the scope is exited.

Leave A Comment

Receive the latest news in your email
Table of content
Related articles