What is the purpose of the `defer` statement?

iOS interview question for Intermediate practice.

Answer

The defer statement in Swift is used to execute a block of code just before the surrounding scope ends, regardless of whether that scope ends due to a normal execution flow or due to an error. This makes it particularly useful for handling cleanup actions, like closing files, releasing resources, or undoing changes. The code within the defer block is guaranteed to run, even if exceptions occur. Example: swift func processFile(filename: String) throws - String { guard let fileHandle = FileHandle(forReadingAtPath: filename) else { throw NSError(domain: "FileErrorDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "File not found"]) } defer { fileHandle.closeFile() // Ensures the file is always closed, even if an error occurs } let fileContent = String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8) return fileContent ?? "" //Handle potential nil result from String initializer } do { let content = try processFile(filename: "/path/to/file.txt") print(content) } catch { print("Error processing file: \(error)") } In this example, fileHandle.closeFile() is executed regardless of whether the processFile function completes successfully or throws an error. This prevents resource leaks and ensures a clean exit. Best Practices: Use defer for cleanup tasks only. Don't use it for complex logic that might impact the function's main behavior. Keep the defer block concise. Avoid nested defer statements which can make code harder to understand. Use defer where appropriate, but don't over-use it to the point it obscures your code's logic.

Explanation

The defer statement's behavior is similar to finally blocks in languages like Java or Python, but Swift's defer is more integrated with error handling and the language's design.

Related Questions