How do I use defer statements effectively?

In Swift, the `defer` statement is used to execute a block of code just before the current scope is exited, whether it’s due to returning from a function, breaking out of a loop, or throwing an error. This makes it particularly useful for cleanup tasks, ensuring that necessary finalizing actions are performed regardless of how execution leaves the current context.

Usage of Defer in Swift

You can have multiple defer statements in a single scope, and they will execute in reverse order of their appearance. This helps in situations where you may want to release resources or revert state changes in a structured manner.

Here’s a simple example:

func readFile(filePath: String) {
        var fileResource: FileHandle!
        defer {
            fileResource.closeFile()
        }
        
        do {
            fileResource = FileHandle.forReading(atPath: filePath)
            guard fileResource != nil else {
                print("Cannot open file!")
                return
            }
            // Read and process the file data...
        } catch {
            print("Error reading file!")
        }
    }
    

Swift Defer Cleanup Resource Management Error Handling