As developers, we spend a great deal of our time checking for conditions that do not meet our requirements (i.e.  nil objects, out of range values, etc).

Before we even start our routines, we always want to take a defensive stance and check our preconditions first. This is sometimes referred to as the Bouncer Pattern. (Because, we’re stopping those bad values at the door!)

This has long been accepted as canon for proper architecture. Though, why can’t we check for the values we actually want instead? With Swift 2.0’s guard statement, Apple has made a progressive step forward.

Rather than just talking about it, let’s take a look at some Swift 1.2 code:


if foo == nil || foo < minValue {
   // preconditions fail
   return
}
// all good, continue method

With the new Swift 2.0 guard statement, we can instead check for the values we actually want.


guard let foo == foo where foo > minValue else {
   // preconditions fail
   return
}
// all good, continue method

As you can guess by the code example, the guard statement provides optional binding. However, it is not limited to optionals.

Logically, this progressive line of thinking might be easier for some people to process. Instead of checking for all the conditions they don’t want, now developers can check for what they do want, and still write well-architected code.

It’s a bold step forward. Well done, Apple!

 App Development

, , , , , ,


Matthew's Blog
Home   Blog   LinkedIn   Contact Me
Connect on LinkedIn, Google+,

2 Comments

  1. Reply

    Ilija

    June 14, 2015

    What about `assert`? Truth-y checks have been used for quite a while…

    • Reply

      Matthew Fecher

      June 14, 2015

      Hello Llija, great point! I also enjoy assert and it is an excellent example of DbC design. From the initial push, it appears that Apple is hoping ‘guard’ will be a bit more mainstream…


Would you like to share your thoughts?

Your email address will not be published. Required fields are marked *

Current focus: App & Web Development
Preferred Environments: OS X, iOS, Xcode, Sublime Text
Current skills: SWIFT, Objective-C, iOS SDK, CoreData, CoreAudio, JavaScript, HTML5, CSS, Wordpress
Degree: Bachelors of Science in Computer Information Systems Technology
from PURDUE University


© Website by Matthew Fecher
Denver, Colorado, USA.

top