Is "&&" equal to ","?

var a: Bool
var b: Bool

if a && b {
    //todo
}

if a, b {
    //todo
}

What's the difference and which one is better (without optional binding)

3 Likes

The two examples you wrote above should be semantically equivalent (for example, they both short-circuit if the first value is false). Neither really has an advantage over the other, it's more of a stylistic choice. You can see that they compile to pretty much the same assembly here: https://godbolt.org/z/cXA5JT

3 Likes

Is there any suggestion that which style is good?

I wonder if this is even intentional, or just a result of the grammar allowing it:

Personally, I’d recommend you stick with && as that makes it clear you’re checking two Boolean values.

1 Like

Using a comma is more useful in if-let and guard-let statements:

guard let bool = optionalBool, bool && foo == bar else { }

Using && instead of , results in the if statement having only one big condition, while using the comma results in a condition-list made of several smaller conditions.
Using comma might be quicker to type check? Since the compiler won’t have to consider eventual operator overloading and precedence groups...

It is a speculation though. Would be interesting to check it :slightly_smiling_face:

I personally prefer to use comma even for simple booleans as it is visually much lighter weight than && IMO. Sometimes when I find that I need to also include an || case alongside, I'll instead rearrange the logic just to avoid using the operator because I think it's kind of ugly. :stuck_out_tongue: I sort of wish there was a more comma-like separator for or.

I wouldn't recommend that, because it becomes inconsistent with boolean expressions used in other contexts, such as arguments to functions (foo(a && b), or assignments (a = b && c), where the , has different meanings.

Although I have to agree that

if somethingWithALongName,
   somethingElse { ... }

Is nicer than having a trailing &&

1 Like

Can’t agree with that as a reason not to use comma in ‘guard’ and ‘if’, really. They’re totally different situations. I can’t recall ever making a typo like this, either, but even if I did, the compiler would almost certainly have caught it. What’s ugly in one context is not necessarily ugly in all others. :stuck_out_tongue:

Yes, with optional binding, if let a = SomeOptional, b is a good style.

1 Like

If a long name is a problem, we should give a better name. Or you can also write like

if somethingWithALongName
    && somethingElse {
}

There is also a difference because a && b does an “autoclosure” of the right operand, and that captures self under some circumstances. A contrived example:

class Foo {
    let a: Bool
    let b: Bool
    init(x: Bool) {
        a = true
        if x && a {
            print("yes")
        }
        b = false
    }
}

causes an

error: 'self' captured by a closure before all members were initialized
if x && a {
        ^

but with

    if x, a {
        print("yes")
    }

it compiles without problems. (I think this difference has been mentioned before in this forum, but I haven't found the post yet.)

14 Likes

Other considerations being equal, I would go with the more orthogonal of the options (if I may express it that way).

&& is more orthogonal in that it is used in more scenarios where boolean AND can be represented.

Where && and , could be used interchangeably, I therefore see && as the more correct choice.

1st) It clearly expresses the intent in a more familiar way (thanks to more orthogonality)
2nd) It means that when , is used, there is an intentional effect of doing so, which helps also make the use of , more expressive.

That's just how I see see, but I'm not a zealot about these thing and open-minded to alternative points of view.

1 Like

I’d argue that they’re not equal, and that the visual clarity plays a role here. We could apply the same logic to guard because it is totally redundant, but guard does have benefit just by its sheer form (+ you must get out of the current scope).

I see , vs && similar to that. Also, I tend to break statements with multiple sub-statements into multiple line, and I find it awkward to do it with &&.

2 Likes

I always go with commas when possible because the second & is redundant in Swift.

1 Like

I'm not sure an argument exists.

The example given in the OP is:

var a: Bool
var b: Bool

if a && b {
    //todo
}

if a, b {
    //todo
}

If you wish to ignore that scenario then there are obviously any number of interesting points to be made. But if the OP scenario is to be addressed then there is no dispute about equality.

Given two booleans, a and b, if both are true then perform some task. That's the clear intent here.

Both of the above achieve this, so they are equal. I see no reason to dispute this.

The first does it using a commonly recognised style, the second does it by way of an interesting side-effect, perhaps of syntax which may or may not be intentional, and, I'd wager, a way unknown to many until this post.

So the difference between the two is that the 2nd is more unfamiliar to more people. Is that what you seek?

I said they’re different enough, and , has its place. The discussion quickly evolved past the original a and b example to the recommendation for style guide. That’s why I talk generally that for longer syntax it is less awkward to use ,. Perhaps I’m not clear enough on that, I apologize.

That sounds like an interesting discussion but how does it reconcile with the Swift.org docs that say:

I’m (pretty) sure that text long predate the syntax though the actual history doesn’t really matter. It is still valid to write in both syntaxes and there’s no strict recommendation. It’s just a stylistic choice after all.

No apology need, it's just a friendly discussion (I hope) :grinning:

I do appreciate the broader context, which I tried to express with:

I genuinely think Swift is an exceptional language (I've programmed for 40 years and lost count of how many languages I've used in that time). For me what makes it shine is the attention to detail and respect for the various paradigms it draws from while also respecting its own goals.

I have to confess I never considered && to have readability issues, but that may be simply because I learned logic circuits and electronics before getting into programming.

3 Likes
Terms of Service

Privacy Policy

Cookie Policy