Bailing out early with guard blocks

With the launch of Swift 2 we got a new keyword that got this developer a little rattled. Guard statements are pretty ingenious when writing “defensive code”. Every Objective-C programmer should be familiar with defensive programming. With this technique, you try to “bail out” as early as possible when you determine the code you’re about to run is not satisfied with the given input.

Guard statements let’s you specify some constraint that must be satisfied by the code that follows after the guard statement. You are also required to specify what happens if the constraint is not satisfied. Furthermore guard enforces the use of return. In earlier Swift code you would have used regular if-else statements to bail out early. But with guard statements the compiler will save you if you don’t properly return from the unsatisfied constraint.

Here is a rather long but typical example of where guard statements are very handy. This function didPressLogIn is called when the Log In button in a screen is tapped. We want to make sure that the button does not cause the program to perform an additional log in request if it is tapped while an existing request is performed. Therefore we bail out early. Later on we validate the log in form. if the form is not valid we need to remember that we are not trying to log in anymore, but more importantly we need to return execution so we don’t send the log in request. The guard statement will complain if we don’t include the return.

Guard statements can become even more powerfull when combined with let assignments. Below we are binding the result of request in a variable for later use by the finishSignUp function. If the result.okValue is nil then the guard is not satisfied, but if it is not nil, the value will be bound to the user variable. We are restricting the guard further with a where clause.

Guards are powerfull. If you’re not using them, you should reconsider.