Blog

Software Development Preston / Code  / Defer keyword in Swift

Defer keyword in Swift

Defer keyword in Swift

One of the features added in Swift 2 was the new keyword ‘defer’. I thought I’d write a quick post to explain why this is a great addition to the language and where it comes in useful.

Swift now has exceptions and guard features which encourage early return over nesting logic which is always something I have been in favour of. Early return does however bring some challenges as sometimes you need to run some cleanup code at the point of return regardless of where you return (think closing a HUD, closing files or freeing some resources) which leads to repeating code at each point of return.

This is where defer comes in. By providing a safe and clean way to define any code that must be run at the point of return at the start of the function you can guarantee this code will be run wherever (or however) you return from the function.

For example, you may have previously done this (pseudo-code):

Now, if any of the features are currently unavailable the file is never closed.

Previously, you would need to copy the line below before every return statement which is not exactly pretty or efficient and if you ever introduce more code that needs to run on return you need to rememeber to copy it into every return block.

Enter defer… With defer you can simply define the block that must run on return at the very beginning of the function and be sure it will run at any and every exit point. Example:

Now closeFile will be executed no matter where you return from the function. Much neater, much cleaner and much more maintainable.

Anyone coming from a C# or Java background will recognise this as something similar to try…finally. However, I prefer not having to wrap the entire code block inside a try{ } block which is something that makes defer much more elegant in my opinion.

Facebook Comments

No Comments

Sorry, the comment form is closed at this time.