Swift - Combining Logical Operators

Introduction

While the logical operators work with two operands, it is common to combine them together in a single expression:

Demo

var condition1 = false
var condition2 = true
var condition3 = true
if condition1 && condition2  || condition3  {
    print("Do something")
}

Result

In this example, the first condition is evaluated first:

condition1   (false) && condition2   (true)

It then takes the result of the evaluation (which is false ) and evaluates it with the next operand:

false  || condition3   (true)

The result of this expression is true , and the line "Do something" is printed.

Sometimes, however, you may not want the evaluation of the expressions to go from left to right.

Consider the following example:

var happy = false
var skyIsClear = true
var holiday = true

Suppose you want to go out only if you are happy and the sky is either clear or it is holiday.

In this case you would write the expression as follows:

Demo

var happy = false
var skyIsClear = true
var holiday = true
if happy && (skyIsClear || holiday) {
    print("Let's go out!")
}

Note the parentheses in the expression:

(skyIsClear || holiday)

This expression needs to be evaluated first. In this example, it evaluates to true.

Next, it evaluates with the first operand:

happy   (false) &&  true

The final expression evaluates to false , which means you are not going out today.

The next example doesn't use the parentheses:

happy && skyIsClear || holiday

Therefore, the preceding expression yields a different result:

happy  (false) && skyIsClear (true) =  false
false  || holiday (true) = true

Using parentheses to group related conditions together so that they are evaluated first.

Even if it is redundant sometimes, parentheses make your code more readable.

Related Topic