Skip to content

What’s new in Swift 2: guard

I have been refraining from writing a “What’s new in Swift 2” post for too long. I need to do it, because I need to really wrap my mind around the new stuff, and there is no better way of doing that than writing about it, but on the other hand, there are plenty of “What’s new” post already.

So, I’ve decided that I’m going to do it, anyway, but one step at a time. And, today it is time for guard.

The problem guard solves.

Let’s assume that we have a function that needs to divide two numbers And for the shake of the example, we want those two numbers to be optionals.

This would be, more or less, the Objective-C way of doing it, just translating the code to Swift.

The good thing is we bounce out of the function immediately. The bad thing is well, overall ugliness and force-unwrapping, and kittens dying.

So, if we do it The Swift Way, we could something like this:

It gets better, but still, the function looks, at least to me, a little bit upside down. We don’t bounce out of it immediately, we first check the happy path, and go through it, if possible. And in doing so, readability drops.

We could refactor that function, to have only one return point. In a way, the code would look neater, but we are not bouncing early, which was kind of the point of the whole thing.

The way guard solves it.

So, here comes guard to the rescue. Basically, guard statements only run if the conditions are not met, which is precisely what we want here:

Final words.

I guess there is not much more to add at this point. guard makes the code neater and more legible.

In my book, that makes it a keeper.

One Comment

Leave a Reply

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