Defer keyword in Swift

Payal Kandlur
1 min readSep 12, 2021

--

The defer keyword was introduced in Swift 2.0. A defer keyword is used to execute the piece of code just before handing over the program control outside of the scope that the statement appears in.

In normal terms, imagine you want to go on a trip, but you got to choose one among the two places which come on the same way and pay for the trip at the end, but no matter what, in the end, you got to pay. This “got to pay” part of this whole scenario is what defer is.

Swift’s defer keyword lets us set up some work to be performed when the current scope exits.

func updateImage() {​ 
defer {​ print("Did update image") }​

print("Will update image")
imageView.image = updatedImage
}​
// Will update Image
// Did update image

Do you see what happens? It prints the print statement in the defer after the function has been executed, just before leaving the function scope.

Best usage scenario

The most common use case example would be when handling access to files. A filehandle requires to be closed once the access has been finished. You can benefit from the defer statement to ensure you don’t forget to do this.

In the case of multiple defer statements, it executes in reverse, that is, a bottom to top fashion.

That's all!😊 Comment to add your thoughts and queries if any.

--

--

Responses (1)