Swift - Operator AND Operator

Introduction

The logical AND operator creates a logical expression (a && b ) where both a and b must be true in order to evaluate to true.

The following table shows how the AND operator works on two values.

Both a and b must be true in order for the expression to be true.

a b a && b
truetrue true
truefalse false
false true false
false false false

Consider the following example:

Demo

var happy = true
var raining = false

if happy && !raining {
    print("good!")
}

Result

Here, the line "good!" will only be printed if you are happy and it is not raining.

Swift does not require you to wrap an expression using a pair of parentheses, but you can add it for readability:

if  ( happy && !raining )  {
    print("good!")
}

Swift supports short-circuit evaluation for evaluating the AND expression.

If the first value is false, the second value will not be evaluated because the logical AND operator requires both values to be true.

Related Topic