10. How to use defer in Swift?

It will take about 1 minutes to finish reading this article.

The defer keyword in Swift is used to delay the execution of a block of code, typically to perform cleanup or necessary finalization tasks before the current scope ends. The code within a defer statement is executed regardless of whether the block is exited due to normal circumstances or due to an exception being thrown.

Here’s an example of a defer statement:

1
2
3
4
5
6
7
8
9
func processFile() {
print("Opening file")
defer {
print("Closing file")
}
// File processing logic goes here
print("Processing file")
}

In the example above, the defer statement ensures that the file is properly closed regardless of whether the file processing logic is executed successfully. Even if an exception occurs during the file processing or the function is exited prematurely, the code within the defer statement will still be executed, guaranteeing the proper release of resources or the execution of necessary cleanup operations.

The use cases for the defer statement include, but are not limited to:

  1. Ensuring the proper closure or release of resources after opening them within a function.

  2. Performing necessary finalization tasks after a series of operations, such as releasing memory, closing files, or cleaning up temporary data.

  3. Guaranteeing the safe release of resources, even in the event of an exception during processing.