Swift - Function defer Keyword


The defer keyword wraps code to run at a later time.

You can use defer to write the teardown code next to your setup code.

Code you put in a defer block will run when the current flow of execution leaves the current scope.

The current scope includes the current function, loop body, and so on:


func doSomeWork() { 
    print("Getting started!") 
    defer { //from w  w w .  j a  va2  s . com
        print("All done!") 
    print("Getting to work!") 


The defer block of code is run in between the end of the final print statement, but before the closing brace.

You can do clean up work and return a value.

defer is a resource management and code style technique, not a means of implementing asynchronous code!