[swift-evolution] Nil coalescing operator precedence

Haravikk swift-evolution at haravikk.me
Wed Jun 15 03:31:42 CDT 2016


> On 15 Jun 2016, at 00:21, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> I don't know that it's feasible to warn on every use of operators with mixed precedence. Doing so would effectively do away with the concept of precedence at all, since everything would have to be grouped by parentheses in order to avoid warnings. (The core team has been pretty clear that there will be no 'optional' warnings, and in certain organizations warnings are regarded as errors.)

Personally I’m against precedence entirely, as I’m terrible at remembering the order and even if I could I’d still see myself making tons of mistakes, as a result I use parenthesis in all but the simplest statements just to be absolutely clear. The problem with precedence is that while it lets the compiler choose a logical order to process expressions, you can never be sure that it’s actually the order the user intended.

Still, I may be in the minority, not sure, maybe other people are happier with math operator precedence than I am. However, I think that effectively forcing parenthesis on ?? and ?: may be okay; most of the time these are used in simple, non-ambiguous cases (either on their own, or with an assignment), so parenthesis shouldn’t be needed, but anywhere they’re within larger statements I think it makes sense to encourage parenthesis use so the compiler can be certain it isn’t guessing at your meaning. I mean it’s kind of like forcing a defensive coding style, but that’s not necessarily a bad thing; I’ve learned from experience that I suck at operator precedence and instead of wasting time looking it up to be sure, hurling a bunch of parenthesis in place not only clarifies my intent, but avoids the problem entirely, I wish more people would do it, as I still run into cases in other people’s code where it takes some time to figure out meaning (usually because these operator precedence obsessed monsters don’t leave comments either ;)

Increasing the precedence won’t help IMO, as it remains just as possible for a user to make a mistake, plus we run the risk of changing the result of currently correct code that works fine with the current precedence but will suddenly give different results if evaluated sooner.

So yeah, I think recommending parenthesis is a good compromise, and good style to encourage when using these operators in more complex cases, not just for avoiding mistakes but also to make the code more readable for others.


More information about the swift-evolution mailing list