Skip to main content

Posts

Showing posts from July, 2023

What is the defer statement and what is the use of defer statement?

Defer Statement: Introduced in Swift 2.0, The Swift Defer statement isn't something you'll need to use often.  What is Defer? A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in. In simple words, defer is an operator used with closure where you include a piece of code that is supposed to be executed at the very end of the current scope. Syntax defer { statements } Example func f () { defer { print ( "defer statement executed" ) } print ( "End of function" ) } f () // Prints "End of function" // Prints "defer statement executed" The above example defer statement was executed after the print statement after the end of function f() 's Scope. Multiple Defer One of the most powerful features of defer statement is that you can stack up multiple deferred pieces of work, and Swift will ensure they all get executed. If you use multiple de...