We already know multiple optional bindings can be used in a single if/guard statement by separating them with commas, but not with &&
e.g.
// Works as expected
if let a = someOpt, b = someOtherOpt {
}
// Crashes
if let a = someOpt && b = someOtherOpt {
}
Playing around with playgrounds, the comma-style format also seems to work for boolean conditions though I can't find this mentioned anywhere. e.g.
if 1 == 1, 2 == 2 {
}
// Seems to be the same as
if 1 == 1 && 2 == 2 {
}
Is this an accepted method for evaluating multiple boolean conditions, and is the behaviour of ,
identical to that of &&
or are they technically different?
In Swift 3, the
where
keyword in condition clauses were replaced by a comma instead.So a statement like
if 1 == 1, 2 == 2 {}
is saying "if 1 equals 1 where 2 equals 2..."It's probably easiest to read a conditional statement with an
&&
instead of a,
, but the results are the same.You can read more about the details of the change in Swift 3 in the Swift Evolution proposal: https://github.com/apple/swift-evolution/blob/master/proposals/0099-conditionclauses.md
Actually the result is not the same. Say that you have 2 statements in an if and && between them. If in the first one you create a let using optional binding, you won't be able to see it in the second statement. Instead, using a comma, you will.
Comma example:
&& Example:
Hope this helps.
When pattern matching a associated value in a switch, it matters when using a
,
or&&
. One compiles, the other won't (Swift 5.1). This compiles (&&
):This won't (
,
):https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_condition-list
The Swift grammar says that the
if
statementcondition-list
can be composed by multiplecondition
separated by commas,
A simple condition can be a boolean
expression
, aoptional-binding-condition
or other things:So, using the comma to separate multiple expressions is perfectly fine.
Here is a case where they are sufficiently different as to require the
,
. The following code will yieldThis is due to the definition of && on Bool:
The
selectedIndex < self.profiles.count
on the RHS is caught in a closure.Changing the
&&
to,
will get rid of the error. Unfortunately, I'm not sure how,
is defined, but I thought that this was interesting.When it comes to evaluating boolean comma-separated conditions, the easies way to think of a comma is a pair or brackets. So, if you have
It gets transformed into