Use defer Statement for Cleanup in Swift
Written by Team Kodeco
The defer
statement in Swift allows you to execute a block of code when the current scope is exited, regardless of how control leaves the scope. This can be useful for performing cleanup tasks, such as closing file handles or freeing resources, that must be executed even if an error occurs.
Here is an example of using defer
to ensure that a file handle is closed when a function exits:
import Foundation
func readFile() throws {
let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: "file.txt"))
defer {
fileHandle.closeFile()
}
// read data from file
let data = fileHandle.readDataToEndOfFile()
// process data
// ...
}
In this example, the defer
statement is used to close the file handle, regardless of whether the readFile
function completes successfully or throws an error.
It’s important to note that the defer
statement is executed in reverse order of the order in which they are declared. Which means, if there are multiple defer
statement in a scope the last one declared will be executed first.
func someFunc() {
defer {
print("1st defer")
}
defer {
print("2nd defer")
}
}
someFunc()
// Output:
// 2nd defer
// 1st defer
Keep in mind that defer
statement isn’t limited to error handling and can be used for any kind of cleanup tasks.