Swift Q & A


How do I use the ‘defer’ statement with functions in Swift?

In Swift, the `defer` statement is a powerful tool for ensuring that certain cleanup or finalization code is executed just before a function returns, regardless of how the function exits—whether it’s through a return statement, an error thrown, or any other means. This makes it particularly useful for resource management, such as closing files, releasing memory, or any other cleanup operations.


Here’s how to use the `defer` statement with functions in Swift:


  1. Placing ‘defer’ Statements: You can place one or multiple `defer` statements within your function. These statements contain the code that you want to execute later, typically at the end of the function’s scope.


  1. Execution Order: The code within `defer` statements is executed in reverse order, meaning the last `defer` statement is executed first, and the first one is executed last.


  1. Guaranteed Execution: Regardless of how the function exits (through a `return` statement, an error, or any other means), the code within the `defer` statements will always be executed. This ensures that you can clean up resources and perform necessary finalization steps reliably.


Here’s a simplified example:

func processFile(_ filename: String) {
    let file = openFile(filename)
    defer {
        closeFile(file) // This will always be executed, ensuring the file is closed.

    // Perform file processing operations here

    if someCondition {
        return // The 'defer' statement is still executed before the function returns.

    // More code

    // The 'defer' statement is executed when the function exits, ensuring cleanup.


In this example, `openFile` opens a file, and `closeFile` closes it. The `defer` statement guarantees that the `closeFile` function will be called, even if the function exits early due to a return statement.


Using `defer` is a best practice for managing resources and ensuring that cleanup tasks are performed reliably in Swift functions, making your code more robust and maintainable.


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