Lesson 018 – Guard

GuardIn our Introduction to Error Handling, we saw some ways to trap error conditions in our programs. However, the goal there is to control program flow when errors are raised from other parts of the program. That can be framework code (like the JSONObjectWithData call) or code that we have written ourselves.


In today’s lesson, I want to talk about Swift’s guard keyword. Guard is a very subtle feature. You can actually program without it and still create a perfectly well-written program. However, guard allows you to express your intent more directly and specifically than the alternatives. In Lesson 016, we ended up with this method, which handles two pre-conditions before attempting the operation.

Enter Guard

The problem with this code is that we have to think of all of the things that we DON’T want instead of describing the things that we do want. This is where the subtle part comes in. Instead of describing the failing conditions, we describe the passing conditions. Those of you familiar with unit testing might see similarities with Assert statements. I’m fairly sure that’s intentional.

Do you see the difference? Instead of saying if (dividend == 0), we say, guard (dividend != 0). Unlike an if statement, there is no “success block” only the else/failure block. If we have success, the code just keeps going. In my contrived example, this is obvious almost no matter which way we do our parameter checking. However, in an example that Apple provides, you can start to see how this is more clear.


As an exercise, I’d like you to think about how you might have done that without guard. I’ve worked through this a few different ways and each time, I have to either use more lines of code, or make the code itself look less elegant. If you can get yourself to think in this “assertion-based” manner, you are going to write much cleaner code.

Add Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.