# 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.

```func divide(x: Int?, y: Int?) -> Double {
if y == nil || y == 0 {
return 0.0
}

return Double(x!)/Double(y!)
}```

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:

```func divide(x: Int?, y: Int?) -> Double {
if let x = x, y = y where y != 0 {
// Things went as expected
return Double(x)/Double(y)
}

// Things went wrong
return 0.0
}```

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.

```func divide(x: Int?, y: Int?) -> Double {
var returnVal = 0.0

if let x = x, y = y where y != 0 {
returnVal = Double(x)/Double(y)
}

return returnVal
}```

## 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:

```func divide(x: Int?, y: Int?) -> Double {

guard let x = x, y = y where y != 0 else {
return 0.0
}

return Double(x)/Double(y)
}```

## 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.