Bob Roebling
Aug 31, 2018 · 1 min read

Hey Ion, guard statements are similar to if let statements, their purpose is to ensure an optional variable has a value before attempting to use them.

I know it’s a little confusing because standard if statements check for booleans, whereas if let and guard statements check for actual values.

In your case you want to use a guard statement ensuring that x is not nil. This unwraps it so we can use it in a Boolean.

Another way is to use a regular if statement to first check if x is not nil, then check if x is greater than zero. This works because if statements evaluate left to right and bail out as soon as it has a definite false.

You’d still have an wrapped optional but it’s safe to force unwrap the optional inside of the if statement body.

    Bob Roebling

    Written by

    Bob Roebling is a Senior Systems Administrator and tech evangelist with a background in multiple programming languages.