Boolean operators

Booleans are commonly used to compare values. For example, you may have two values and you want to know if they’re equal: either they are (true) or they aren’t (false).

In Swift, you do this using the equality operator, which is denoted by ==:

let doesOneEqualTwo = (1 == 2)

Swift infers that doesOneEqualTwo is a Bool. Clearly, 1 does not equal 2, and therefore doesOneEqualTwo will be false.

Similarly, you can find out if two values are not equal using the != operator:

let doesOneNotEqualTwo = (1 != 2)

This time, the comparison is true because 1 does not equal 2, so

doesOneNotEqualTwo will be true.

The prefix ! operator, also called the not-operator, toggles true to false and false to true. Another way to write the above is:

let alsoTrue = !(1 == 2)

Because 1 does not equal 2, (1==2) is false, and then ! flips it to true.

Two more operators let you determine if a value is greater than (>) or less than (<) another value. You’ll likely know these from mathematics:

let isOneGreaterThanTwo = (1 > 2)

let isOneLessThanTwo = (1 < 2)

And it’s not rocket science to work out that isOneGreaterThanTwo will equal false

and isOneLessThanTwo will equal true.

There’s also an operator that lets you test if a value is less than or equal to another value: <=. It’s a combination of < and ==, and will therefore return true if the first value is either less than the second value or equal to it.

Similarly, there’s an operator that lets you test if a value is greater than or equal to another — you may have guessed that it’s >=.

results matching ""

    No results matching ""