[swift-evolution] [Pitch]: Require parenthesis for ternary operator '?:' or change its priority

Anton Zhilin antonyzhilin at gmail.com
Sat Sep 3 07:29:24 CDT 2016

With the replacement, I would prefer just "then-else", which would still
clearly carry the meaning of low priority. But yes, this option was
explicitly rejected. Unfortunately.

I also agree that changing the priority is not a solution. But how about
removing priority?

The following expression:
`s << (x == 10) ? "10" : "not 10"`
Is currently parsed as
`(s << (x == 10)) ? "10" : "not 10"`

With such a change, the compiler would make you add outer parentheses and
find a bug, by the way:
`s << ((x == 10) ? "10" : "not 10")`

Should this apply to assignment operators?
`s += (x == 10) ? "10" : "not 10"  // error?`

I think such caveats of `?:` are worth creating a proposal, at least.

2016-09-03 14:21 GMT+03:00 Thorsten Seitz via swift-evolution <
swift-evolution at swift.org>:

> The problem you describe is not the priority of the ternary operator but
> that developers just assume a priority without checking (or learning)
> whether their assumption is correct. Changing the priority won't solve that
> problem, it would only shift the problem over to those developers assuming
> the other priority. Worse, it would create this problem for those
> developers knowing the correct priority, because they now have to relearn
> the new priority with the added difficulty of the priority being different
> from C.
> I'm not sure whether the problem really is one (other operators have
> priorities too, which have to be learned), but assuming for the moment that
> it is, a solution would be to replace the ternary operator with an
> if-expression: *if* condition *then* expr1 *else* expr2
> This would enclose the condition between two keywords and thereby be free
> of misunderstandings.
> Replacing the ternary operator is on the commonly asked changes list,
> though, and therefore requires new arguments/insights why a replacement
> would make sense. I think the possibly confusing priority has been
> discussed already in the past and therefore wouldn't count as new insight,
> though I'm not quite sure.
> -Thorsten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160903/1d9c0da8/attachment.html>

More information about the swift-evolution mailing list