Swift Q & A


What is the purpose of ‘defer’ in Swift?

In the world of Swift development, the ‘defer’ keyword plays a crucial role in ensuring the proper execution of cleanup code. Essentially, ‘defer’ allows you to postpone the execution of a block of code until the current scope exits, whether that’s due to normal flow or due to an error. This is immensely helpful in scenarios where you need to perform tasks like resource cleanup, file closure, or any action that should always be executed, regardless of how the code block exits.


When you use ‘defer’, you’re essentially creating a deferred closure that captures the current state and context. The closure is then added to a stack, and when the enclosing scope exits, the closures are executed in reverse order, from the last ‘defer’ statement to the first. This ensures that even if you have multiple ‘defer’ statements within a function, they will be executed in a last-in, first-out (LIFO) manner.


For example, if you’re working with file operations, you can open a file at the beginning of a function and use ‘defer’ to guarantee that the file will be closed when the function exits, no matter how it exits—whether it’s due to a return statement or an error being thrown. This helps in maintaining clean and reliable code by centralizing cleanup tasks and making your code more robust.


In summary, ‘defer’ in Swift is a powerful tool for managing resource cleanup and ensuring that critical tasks are executed before exiting a scope, promoting code reliability and maintainability.


Previously at
Flag Argentina
time icon
Experienced iOS Engineer with 7+ years mastering Swift. Created fintech solutions, enhanced biopharma apps, and transformed retail experiences.