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 ww. ja va 2 s . c o m print("All done!") } print("Getting to work!") } doSomeWork()
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!