Swift Defer Statement Example

1. Introduction

Swift’s defer keyword provides a powerful way to specify a block of code that needs to be executed when execution leaves the current block of code. This ensures that cleanup or other necessary tasks are executed before a function returns, regardless of how it returns.

2. Source Code Example

func readFile(fileName: String) {
    print("Opening file: \(fileName)")

    // Simulate file reading
    defer {
        // This code block will be executed just before the function returns
        print("Closing file: \(fileName)")

    // Some dummy conditions to simulate potential early returns
    if fileName.isEmpty {
        print("File name is empty. Exiting without reading.")

    if fileName.starts(with: "error") {
        print("Encountered an error with file name. Exiting.")

    print("Reading file content...")

readFile(fileName: "document.txt")
readFile(fileName: "")
readFile(fileName: "errorDocument.txt")


Opening file: document.txt
Reading file content...
Closing file: document.txt
Opening file:
File name is empty. Exiting without reading.
Closing file:
Opening file: errorDocument.txt
Encountered an error with file name. Exiting.
Closing file: errorDocument.txt

3. Step By Step Explanation

1. We define a readFile(fileName:) function that simulates reading a file based on its name.

2. At the start of the function, we print a message indicating that we're opening the file.

3. We then introduce a defer block. The code within this block (in this case, printing a message about closing the file) will execute just before the function exits, regardless of where or how the function returns.

4. We have two conditional checks that can potentially cause the function to return early. One checks if the file name is empty, and the other checks if the file name starts with the word "error".

5. If none of the early return conditions are met, we simulate reading the file content.

6. We then call the readFile(fileName:) function three times to showcase the behavior of the defer block in different scenarios.