func addOne() -> Bool {
x += 1
print("111")
return true
}
if true || addOne() && addOne() && addOne(){
print("open the door")
} else {
print("can't open the door")
}
I knew that logical operators are calculated from left to right but in this case addOne
function doesn't called in this condition.
So x
value is 0
and I expected 2
How to solve this logical operators order?
It's called Short-circuit Evaluation and it means when a statement stops evaluation as soon as an outcome is determined. The parts of an expression containing &&
or ||
operators are evaluated only until it’s known whether the condition is true or false. This speeds up the execution of expression evaluation.
So in your code true || addOne() && addOne() && addOne()
is known to be true
as soon as you find true
in your expression. In general true || whatever
will always be true, so there is no need to evaluate whatever
.
&&
has precedence over ||
so :
true || addOne() && addOne() && addOne()
is equivalent to :
true || (addOne() && addOne() && addOne())
And we already know that true
OR whatever
is true, so whatever
won't be evaluated.
To change the default precedence in your expression use parentheses where you see fit. For example:
(true || addOne()) && (addOne() && addOne())
In this case, the first addOne()
won't be evaluated, But the second and third will be, since true
AND something
is something
. And thus, in this case, x would be equal to 2 (supposing that initially x = 0).
Here is a final example (I suppose you get it by now, if not let me know in the comments):
if (true || addOne() && addOne()) && addOne()
In this case, there is an OR between true
and addOne() && addOne()
. Without evaluating addOne() && addOne()
we already know that true || addOne() && addOne()
is true
. So the expression could be simplified to true && addOne()
. Here we have to evaluate addOne()
, which means, x
will equal 1
.
Swift operators belong to Precedence Groups (or levels) which are used to decide which operation has more priority in the evaluation of an expression. A higher precedence level means more priority.
The logical AND &&
belongs to the LogicalConjunctionPrecedence group, which has a higher precedence than the LogicalDisjunctionPrecedence group, to which the logical OR ||
belongs to. And thus &&
has more precedence than ||
.
To learn more about operator precedence groups/levels, have a look right at the bottom of this, or that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments