Guard! Guard!

Swift 2 introduced the guard keyword, a handy bit of syntactic sugar with semantics similar to a debugging assert. It’s pure sugar, nothing more than an alternate if construction, but I’ve found that liberal use of guard has made my code far more readable with very little effort.

Basically, guard is a sort of inverse if. You could just as easily write the (hilariously contrived) above example as:

I strongly prefer the guard version, though, as I find the guard...else line to be much more explicit than the narrow and easily-overlooked !. guard really comes into its own, however, when dealing with optionals. I often find that I end up with a lot of code like:

This is fine, but it feels like inverted logic. I'd far rather take care of the error cases up front, and guard lets me do just that:

Leave a Reply

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