- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Is Defer in Swift?
In this tutorial, you will learn what the defer keyword is and how it can be used in Swift. You will see in what situations you can use the defer keyword.
What is defer?
A defer is a statement that is used for executing code just before transferring program control outside of the scope that the statement appears.
The defer statement is not something you will need to use often in Swift. It will be useful in situations when you want to clean resources before they go out of scope. The defer keyword was introduced in the Swift 2.0 version.
Syntax
// Initial tasks to execute before exiting the scope defer { // perform cleanup operation here // other statements } // further code
Example
var languages = ["Swift", "Objective-C", "Kotlin", "JavaScript", "Java"] func removeLastValue() -> String? { let lastValue = languages.last defer { languages.removeLast() } return lastValue } let lastValue = removeLastValue() print("last value: \(lastValue ?? "")") print("Array: \(languages)")
Output
last value: Optional("Java") Array: ["Swift", "Objective-C", "Kotlin", "JavaScript"]
Explanation
You can see the output and see that languages.removeLast() is written before the return statement in the above example. After completion of the execution of the function, the defer statement will be executed and remove the last element.
Multiple Defers
If multiple defer statements appear in the same scope, the order they appear is the reverse of the order they are executed. The last defined statement is the first to be executed. The most recently deferred thing gets run first – effectively unwinding a stack.
Example
func testingMultipleDefer() { defer { print("one") } defer { print("two") } defer { print("three") } print("end of function") } testingMultipleDefer()
Output
end of function three two one
Defer don't capture value
Deferred statements do not capture the reference or current value of a variable.
Example
func captureTest() { var fullName = "Mohit Chouhan" defer { print(fullName) } fullName = "Mohit Sharma" print(fullName) } captureTest()
Output
Mohit Sharma Mohit Sharma
Note − We can’t break the defer execution or we can’t use return, continue, or break inside the defer block.
A practical example
func writeLog() { let file = openFile() defer { closeFile(file) } print("writing all the logs here...") } func openFile() -> String { return "defer_statement.txt" } func closeFile(_ fileName: String) { print("closing file: \(fileName)") } writeLog()
Output
writing all the logs here... closing file: defer_statement.txt
Even as you make changes to an opened file, if you return or exit this function at the end or in the middle of the function, the defer block ensures that the file will be closed.
Points to remember about defer
A defer shouldn't try to exit the current scope because 'return' is there for this.
Before leaving the current scope, perform such tasks (like cleaning up the resources) in the defer block.
It is actually guaranteed to be executed regardless of how execution leaves the current scope.
A defer statement is only executed when execution leaves the current scope not when the defer statement is encountered.
Conclusion
Swift's defer statements can be very useful in some cases for cleaning up resources. The defer statement will keep your iOS application code running smoothly, even if a team member updates a method or adds a conditional statement. defer executes no matter how we exit and future proofs projects from changes that may alter the scope flow, reducing the possibility of an error.