Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a comma separated conditional and one that uses a double ampersand [duplicate]

I've recently come across this type of scenario using if/let and understand what it does thanks to this post. To my understanding, both conditions need to be met before the proceeding block is executed. I now have come to a point where I've seen it in a regular conditional statement:

if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil {
    return false
} else {
    return true
}

What's the difference between doing the above and simply using && as seen below?:

if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
    return false
} else {
    return true
}
like image 548
Carl Edwards Avatar asked Jul 14 '17 14:07

Carl Edwards


People also ask

What are the uses of comma and conditional (?) Operators?

The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand. First the left operand of the comma operator is evaluated, which increments x from 1 to 2.

What does a comma mean in an if statement?

Posted December 12, 2007 by constant-content in Freelance Writing Tips. “If, then” statements require commas to separate the two clauses that result. If I use correct punctuation, then I will include commas where necessary.

What does a comma mean in an if statement Java?

The programmer has used the comma operator to provide two unrelated expressions in a single statement. Because it's a single statement, both expressions are "inside" the if condition.

What is the purpose of comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.


2 Answers

There does not appear to be a difference between using && for grouping conditionals and using commas. I too have so far only seen it used with optional binding, but apparently it also works for regular conditionals, as the following snippet works fine.

let bool1 = true;
let bool2 = true;

if bool1 , bool2 {
    print("true");
} else {
    print("false")
}
like image 141
TheBaj Avatar answered Sep 20 '22 08:09

TheBaj


The comma is used when optional binding with boolean conditions, for example if let a = a, a.isValid() whereas && is a typical AND operator

like image 32
Keydose Avatar answered Sep 21 '22 08:09

Keydose