[swift-evolution] ternary operator ?: suggestion

Jakob Egger jakob at eggerapps.at
Mon Dec 14 02:49:50 CST 2015

> On 13 Dec 2015, at 20:31, Paul Ossenbruggen <possen at gmail.com <mailto:possen at gmail.com>> wrote:
>> I really don't like the "if cond then expr1 else expr2".
>> 1) First of all, it's extremely verbose. It's almost as bad as the SQL construct "case when cond then expr1 else expr2 end”.
> Yeah it adds a few characters overall. What used to be 2 chars now takes 10. Clarity is preferred though by many. I head frequently people telling users to never use ternary operators because they are confusing to read. 

I don't see the "improved" clarity.

Without syntax highlighting, and no indentation to help, it becomes impossible to read. Compare:

let x = if cond then expr1 else expr2
let x = cond ? expr1 : expr2

The former looks just like a random English sentence, the latter is obviously a ternary expression (to my trained eye)

The ternary operator exists in very many languages, and therefore many programmers are familiar with them.

If the purpose is to make the language easier to understand for novice programmers, maybe you could use "when" instead of "if", for example:

let x = when cond then expr1 else expr2

This has several advantages:

1) The difference between statements and expressions becomes trivial:
- "if" is a statement
- "when" is an expression

2) it becomes easier to google. "swift when" might get better results compared to "swift ?" or "swift if"

3) people familiar with SQL will recognise the functional WHEN expression

4) Of course it is even longer, but at this point, who cares.


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

More information about the swift-evolution mailing list