Instead of relying on the compiler to set operator precedence, we can do so ourselves by wrapping a logical expression in parentheses, ()
. The use of parentheses also makes our code easier to read and interpret.
Assume the following logical expression with multiple logical operators:
true || true && false && true
The order of execution may seem unclear at first but following Swift’s operator precedence rules, we achieve the Boolean outcome, true
:
If we wanted more control of the evaluation of this expression, we can use parentheses to direct order of execution and improve the expression’s readability:
(true || true) && (false && true)
Notice how although the expressions utilize the same operators, their outcomes are different. The presence of parentheses overrides Swift’s operator precedence rules and dictates order of operations.
Instructions
In Practice.swift, we’ve set up multiple expressions that are missing certain logical operators.
Add a logical operator, &&
or ||
, in place of ___
to complete the logical expressions.
bool1
andbool2
should betrue
.bool3
should befalse
.
Note: You will see an error in the terminal on the right if there are still any ___
present in your code. The error should go away after you’ve replaced each ___
with an operator.