During the announcement of Swift 2.0 at WWDC 2015 I was very excited to see what new features they had put in the language. So when the Swift 2.0 features where presented on one of the slides I saw a lot of cool things that piqued my interest. At first I was wondering what a guard was because we already have guards in Swift in the form of the pattern matching in the switch statement with the 'where' keyword (at least if you compare how guard and where works in Haskell). After reading what guards in Swift was I understod how to use them but I felt like they didn't really add anything to the language. But after adopting 'guard's in my own projects I think this features have aided Swift in the most important feature a language can have, tools to write clear and readable code.
I will try to show you the power of 'guard' and give my opinion, when and why you should use it. As I am one of the most original people on the internet I've decide to demonstrate 'guard's with an addition function. But not an ordinary addition function because this functions will return a nil optional if the first argument is not even. To make my example code clearer and easier to read I have extended the IntegerType protocol with a computed property that checks if the integer is even or not.
In the first attempt to implement this function one would probably do some thing like the code below in Swift pre 2.0. This implementation works as intended but could in my opinion be clearer. First it checks if 'x' and 'y' are not 'nil' and if 'x' is even. If all of this is true then return the result otherwise return '.None' (which is equivalent to nil).
Instead of using 'if let' one could utilize 'guard's to check if the inputs are valid and if they are not it return '.None'. There are two things that make this approach clearer than the other one. First they don't nested code because guard automatically unwraps optional for the rest of the scope. And secondly the guard keyword is used to guard against bad values and makes what is happenin clear for the reader.
But we can do better, let's have two guard statements to separate the validation of the input. By doing it this way it is very clear what input this implementation accepts. This is not something we could do with 'if let' without having to nest and 'if let' in another 'if let'.
I like to keep the nesting of code to a minimum and 'guard's is a great way to achieve it (nobody likes a pyramid of doom). The 'guard's help you divide up the implementation details into understandable chunks of code like input validation and logic.