[swift-evolution] ternary operator ?: suggestion
possen p
possen at gmail.com
Sat Dec 5 12:29:09 CST 2015
The current ternary operator, for this example:
let val = p == 5 ? 10 : 40
Which I have always thought was hard to read but I do like the functionality it provides. That is, in one expression you can compactly get two different values based upon a condition. Swift seems to have adopted the C style ternary operators probably to not completly change everytihg. Similar to the drop of the ++ and -- operator I am proposing that there is to replace the ternary operator to improve readability but continue to provide that functionality.
Recommendation: most readable but changes rules about if-else always having braces and puts the “if” at end. It is only a little bit longer than the original. I think it is clearer to have the conditional at the end so the assignment part is where the variable is assigned. This also does not introduce new keywords or operators.
let val = 10 else 40 if p == 5
In looking at the Nil-Coalescing operator there is a similar idea but it is really not the same. In that the left hand side of the ?? operator returns itself when non nil, and the behavior of the ternary operator is different. It is also harder to read.
let val = 10 ?? 40 if p = 5
I also considered a bunch of other possibilities like using “where" or “when" instead of “if”, the python of putting conditional in the middle or the ruby style of “if" returning a value but did not like those.
// python style
let val = 10 if p == 5 else 40
// ruby style
let val = if p == 5 then 10 else 40
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/6e586e90/attachment-0001.html>
More information about the swift-evolution
mailing list