How to use defer in Swift?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

Using defer keyword in Swift code is uncommon. But, It is a very powerful concept for certain use case. The code block inside defer statement is executed just before transferring program control. It does not matter how program control is transferred. I find this concept particularly useful when I need to clean up something inside the function or perform an action that needs to happen even if an error is thrown. Another very common use case is closing the file after a certain operation in FileHandle.

func isFileValueAccessed(_ accessPath: String) -> Bool {
        if let fileHandle = FileHandle(forReadingAtPath: accessPath) {
            print("FileHandle is avaialble!")
            defer {
                fileHandle.closeFile()
                print("File is closed!")
            }
        } else {
            return false
        }
        print("Value is accessed!")
        return true
}

let _ = isFileValueAccessed("dummy_path")

// Output
// FileHandle is avaialble!
// Value is accessed!
// File is closed!

No matter how you exit, the defer statement is executed at the end. We can exit the current scope (The scope can be for in loop, do try-catch block, function body etc.) using single return, multiple returns or break. Here, the defer is executed in every possible case while exiting the scope. Writing the same exit code multiple times is not a smart thing to do.

Multiple defer statements execution order

If multiple defer statements appear in the same scope, the order they appear is the reverse of the order they’re executed.

func printDeferCodeBlocks() {
    defer { print("This") }
    defer { print("is") }
    defer { print("nice") }

    print("Hi")
}

// Output
// Hi 
// nice
// is
// This


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.