History of the question:
Defer was introduced in Swift (inspired by analogs in Go, C#) to guarantee resource cleanup even in the event of errors, exiting a function, or returning values from various points in functions.
Problem:
Premature deallocation, forgotten resource cleanups (e.g., closing files, logging, rollback transactions). Sometimes people confuse the order of execution, mistakenly believing that defer executes at declaration time.
Solution:
Defer is a special block that postpones the execution of code until the end of the current scope, usually a function. All defer statements are executed in reverse order of placement (LIFO). This allows centralized management of resource cleanup, memory deallocation, or transaction rollback.
Code example:
func processFile() { let file = File("/tmp/data.txt") file.open() defer { file.close() print("File closed") } // Work with the file print("Reading data…") }
Key features:
Does the code inside defer execute if the application crashes before exiting the function?
No, the defer code only executes on a proper exit from the scope. If the application crashes (for example, due to a fatal error), the defer will not execute.
Can return be used inside defer?
No, it cannot. The defer block does not allow returning values or exiting the scope, only instructions.
Can defer be used to modify variables declared before defer?
Yes, defer captures values from the current stack at execution time. You can modify values declared before defer, and they will be preserved on exiting the scope.
Code example:
func example() -> Int { var result = 0 defer { result = 42 } return result // defer will execute, the result will be 42 }
The file is opened, but closed only explicitly at the bottom of the function, leaving the file open on errors or early exit from the function.
Pros:
Cons:
Using defer to close the file immediately after opening. Even if an exception occurs or a return from the function happens, the file will be guaranteed to close.
Pros:
Cons: