[swift-evolution] ternary operator ?: suggestion

Al Skipp al_skipp at fastmail.fm
Tue Dec 15 04:34:47 CST 2015

> On 15 Dec 2015, at 06:41, Paul Ossenbruggen via swift-evolution <swift-evolution at swift.org> wrote:
> Agreed, I was thinking to I really want turn something that was 2 characters into 10 and will I really be happy with that at the end of the day. A properly formatted ternary can be quite easy to read, it is when people get sloppy and try to cram too much into one expression that they get really hard to follow. For example,
>     return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
> If formatted like this becomes easier follow the logic (at least to me):
>     return a < b
> 	? b < c 
> 	  ? b 
>           : a < c 
> 	     ? c 
> 	     : a 
> 	: a < c 
> 	  ? a 
> 	  : b < c  
>              ? c 
> 	     : b

I’m happy to make use of the ternary operator, but never in a nested fashion. It looks neat and succinct on first glance, but is quite impenetrable to read. I don’t think there’s a way to make such nested expressions easily comprehensible. Nested ‘if/else/then’ expressions will be equally bewildering.

On a purely stylistic level I think simple, ‘if/then/else’ expressions, would have a more Swift vibe to them than the ternary operator. Well, that would be the case if it didn’t introduce the confusion between expressions and statements.

> I do still however like the Switch Expressions.

I agree. The Switch expression proposal is worth pursuing, it’s something I’d really like to see in the language. One concern I have is that it faces the same dilemma of the ‘if’ expression proposal, that is, how to make the distinction between a statement and an expression unambiguous?

Here’s a suggestion, it might be terrible (I’ve not had my third cup of tea of the morning yet), but how about a different keyword? I know, I feel guilty for the suggestion already, but here it is:

switch == statement
match == expression

The syntax you (@Paul) have already suggested for the feature wouldn’t change, but instead of ‘switch’, it’d use the ‘match’ keyword for the expression form. Good, bad, terrible? What do people think?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151215/aa406463/attachment.html>

More information about the swift-evolution mailing list