Swift Defer Statement


With Swift 2.0 the defer statement ensures code is executed regardless of how the current scope exits. This keeps any “clean-up” code nice and tidy, right next to the initial opening calls without having to repeat yourself for any early exits. WWDC 2015 session “What’s New in Swift” gives a short example I will outline here.

The example they give is you may have a method like this…

At the beginning you start something; in this case you notify the delegate. At the end you notify the delegate again. This seems simple enough, but when you add in multiple exit paths it can quickly become a mess. This is a common case when using error handling.

There are many points at which you want the delegate to call didEndReadingSale(). You even have to create a do-catch to make sure it is called in case of processPerson() throwing an error. This is made worse as time goes on and you may add more to that method.

With Swift 2+ you can instead use the defer statement.

Defer promises that didEndReadingSale() will be called no matter how the current scope exits. And keeps you from having to make special do-catch arrangements when calling processPerson(). If you have been worrying about having many potential paths in your methods, worry no more.

Some important notes from The Swift Programming Language Reference.

  • can’t contain any control transfer statements; break, return, or throw
  • defer statements are executed in reverse order. 2nd defer is executed before 1st defer.
  • defer may be used even when no error handling code is involved

WWDC 2015 Session 106 starting at 43:30, gives a few minute blip about Apple’s reasoning behind defer using this example, and I recommend watching it for yourself.

Also if you haven’t yet learned about swift guard, you can check out my post on that here: Swift Guard Statement

Happy Coding


Recommend and follow me @iJoeCollins on Twitter