Swift Guard Statement
Swift 2.0 brings a lot of new changes to the programming language but some of the most talked about changes are error handling and the guard statement. @natashatherobot has a great post where she shows an example that includes both. Just these two improvements can help your code become more efficient, maintainable, and easier to read.
The guard statement is one of three branch statements in Swift. The other two being the if statement, and the switch statement. It is composed of a conditional statement, a constraining where statement (if you need it), and a required else for when the condition fails or the constraints are not met. What this means is that if something isn’t going right it can immediately transfer program control out of scope.
Why might you want to use this?
If you haven’t checked this out yet do so. Basically it keeps your program from doing any extra work.
Guard also keeps you from cluttering your function with the “pyramid of doom” using if statements with some kind of exit statement in the middle. It’s hard to follow especially if you have calls that happen after each if statement.
But what about statements that only evaluate if something is false and does not employ optional binding?
That’s true. You can accomplish the same thing with an if statement that evaluates false. But then your initial “early exit” intention for the statement can be lost in translation. Another programmer may decide for whatever reason to throw-out your control transfer statement and then all kinds of bugs could show up. Also the compiler won’t catch this.
I think it best to follow readable, compiler safe, coding standards going forward.
And in fact the compiler does enforce this! Winning!
Follow me @iJoeCollins on Twitter