Bo

Booleans in Swift

1 exercise

About Booleans

Swift has a type known as Bool, it is used to represent the values true and false.

Logical operators

Swift has 3 logical operators (!, ||, &&) which are used to combine Bools and make expressions that produce different values.

And(&&)

The and operator in Swift is represented by && and returns true if both values given are true otherwise it returns false. When using the and operator, one Bool be placed on the right side of the && and another one on the left side.

true && true  // true
true && false // false

Or(||)

The or operator in Swift is represented by || and returns true if at least one of values given is true if both of the values are false then it returns false. When using the or operator one bool should be placed on the right side of the || and another one on the left side.

true || true   // true
true || false  // true
false || false // false

Not(!)

The not operator in Swift is represented by ! and returns true if the given Bool is false and returns false if true is given. When using the not operator one Bool should be placed after the operator (!).

!true  // false
!false // true

Using parentheses(())

When working with booleans you can use explicit parentheses to decide which Bools to evaluate first. The result can differ depending on how the parentheses are used. In Swift, what is in parentheses is evaluated first.

true && false && false || true   // true
true && false && (false || true) // false

Since what is in parentheses is evaluated first, in the following example, the not operator will apply to the expression inside parentheses.

!true && false   // false
!(true && false) // true
Note

You should only use parentheses when they affect the result, otherwise, should they be omitted.

Edit via GitHub The link opens in a new window or tab

Learn Booleans