Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "&&" and "," the same in Swift?

Tags:

swift

As the title says, I just came across a case where if && (AND) and , give the same result in Swift. I tested the code below:

let a = 5
let b = 6

if a<6, b>0 {
    print("should be true")
}

if a<6, b<0 {
    print("should be false")
}

if a>6, b>0 {
    print("should be false")
}

if a>6, b<0 {
    print("should be false")
}

It only logs:

should be true

So, the behavior of , is just like &&, am I correct?

like image 878
William Hu Avatar asked Apr 12 '17 10:04

William Hu


People also ask

Are and is meaning?

Updated on April 4, 2022 · Grammar. ​​When deciding whether to use is or are, look at whether the noun is plural or singular. If the noun is singular, use is. If it is plural or there is more than one noun, use are.

Are is verb or not?

The words is and are are forms of the verb be, the most commonly used verb in English. Because they're used so frequently, it's important to know the grammatical and functional difference.

Are in English word?

Are is the plural and the second person singular of the present tense of the verb be1. Are is often shortened to -'re after pronouns in spoken English.

How do you use here?

If the succeeding noun is singular, then you should use “here is.” For example, “Here is a book. ” Because there is only one book, the verb form is singular. If the following noun is plural, use “here are,”.


2 Answers

They can be used in similar situations but that does not mean they are exactly the same.

Consider:

if (a && b) || c

you cannot write

if (a, b) || c

even a && b || c is different from a, b || c.

if a, b is something like

if a {
   if b {
      ...
   }
}

Both expressions have to be evaluated to true but they are still two separate expressions. We shouldn't imagine && there.

Why do we need the , operator?

The operator is needed to combine optional binding with boolean conditions, e.g.

if let a = a, a.isValid() {

becuase && wouldn't help us in such situations.

like image 98
Sulthan Avatar answered Oct 13 '22 09:10

Sulthan


They're different in that a comma will take the lowest precedence possible. i.e everything else will be executed before the commas are checked.

// (true || false) && false
if true || false, false {
    print("I will never be executed")
}

// true || (false && false)
if true || false && false {
    print("I am always executed")
}
like image 37
Declan McKenna Avatar answered Oct 13 '22 10:10

Declan McKenna