Junior — Middle
Could you explain what the keyword Defer means and how it is used in programming?
sobes.tech AI
Answer from AI
The keyword defer in programming (for example, in Swift or Go) is used to postpone the execution of code until the current scope is exited.
In iOS (Swift), defer guarantees the execution of a specific block of code at the end of a function, regardless of how the function terminates — successfully or with an error. This is convenient for releasing resources, closing files, releasing locks, etc.
Example in Swift:
func readFile() {
let file = openFile()
defer {
closeFile(file) // this code will execute at the end of the function
}
// work with the file
if errorOccurred {
return // `defer` will still execute
}
// other operations
}
Thus, defer helps write cleaner and safer code by managing resources.