Can someone help me understand why there is a comma separating the two comparisons rather than a &&? I replaced the comma with an && and the code seemed to work, but I am trying to understand why a comma is used in the example and more importantly how and why Swift uses commas in this way.
The following example demonstrates that a condition-list, when it appears as the condition of an if statement, behaves like a logical && expression, but it is not a logical && expression.
// -------------------------------------------
//
func foo (_ v:Bool) -> Bool {
print ("\(#function): v=\(v)")
return v
}
func bar (_ v:Bool) -> Bool {
print ("\(#function): v=\(v)")
return v
}
func jibber (_ v:Bool) -> Bool {
print ("\(#function): v=\(v)")
return v
}
func test (_ u:Bool, _ v: Bool, _ w:Bool) {
if foo (u), bar (v), jibber (w) {
print ("condition-list: all true.")
}
else {
print ("condition-list: not all true.")
}
}
test (false, false, false)
test (false, true, false)
test (false, false, true)
test (true, false, false)
test (true, true, false)
test (true, true, true)
// A logical && expression
print ("A logical && expression...")
let u = foo (true) && bar (true) && jibber (false)
// A logical && expression?
// let v = foo (true), bar (true), jibber (false) // error
Thank you very much for taking the time to help me out. I should have added that I did spend quite a bit of time searching Apple’s Swift documentation and other sources.
However, I am still confused as to what the benefits are to using a condition list or what a condition list can do that a logical && expression cannot.
So why did the book use this code:
if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil { ...
instead of this:
if (existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil ) {....
I got all my code to compile and run so I don’t technically have a problem. I am just trying to understand this aspect of Swift.
Probably the book is using the first statement in an attempt to introduce the concept of condition lists. (I don’t have the book to verify this.)
As you have discovered, although a condition list is not a boolean expression, both statements do the same thing.
However, the real difference might have something to do with operator-precedence parsing; that is, operator precedence must be taken into account when parsing a boolean expression like the one in the second statement.
The Swift documentation is still evolving. We will just have to wait for the official explanation of the condition lists.