[swift-evolution] ternary operator ?: suggestion
superlopuh at gmail.com
Sun Dec 20 11:14:48 CST 2015
I would like to suggest an alternative to this, and would like to hear what you all think. I think that the biggest problems with the current operators are:
1) They are not clear, by themselves or as a pair.
2) ? is associated with optionals
3) The type of the resulting expression is not immediately clear, as it begins as a boolean, and only after the ? are the actual expressions to be assigned
So, using “booleanExpression”, “anExpression” and “alternativeExpression”:
booleanExpression ? anExpression : alternativeExpression
Paul’s suggested syntax:
?(booleanExpression: anExpression, alternativeExpression)
/* Shouldn’t this be ?(booleanExpression: true: anExpression, false: alternativeExpression), for it to be a true equivalent to switch, or should the boolean shorthand be hard-coded?
(anExpression if booleanExpression else alternativeExpression)
The logic here is:
1) by adding the keywords, the expression becomes more verbose, but also clearer
2) the “?" is gone
3) it begins with an expression of the result type
I think that requiring the parentheses might be a good idea, as it immediately flags the first expression as not being alone, especially if the expression is separated across multiple lines.
Having “if” after the first expression also clearly distinguishes it as different from the “if” used for control flow.
The obvious loss to Paul’s proposal is the loss of switch-level power, but I’m not convinced that this is too bad. Switch statements are great, but can grow quite long with various patterns, and I think should be kept (with current syntax required) as-is.
What do you think?
More information about the swift-evolution