[swift-evolution] ternary operator ?: suggestion
Chris Lattner
clattner at apple.com
Tue Dec 15 16:05:18 CST 2015
> On Dec 15, 2015, at 1:44 PM, Matthew Johnson <matthew at anandabits.com> wrote:
>
>
>> IMO, in order to consider removing ternary, we’d have to introduce something that is *better* than the current ternary operator first.
>
> Do you have any thoughts about what might constitute *better* in your mind no matter how vague they might be? Mostly curious about this.
No, I’m not aware of anything that I’d consider to be better than ?:
In brief, and just MHO, but:
- I agree that ?: is ugly and magic, and is an additional thing people have to learn if coming to swift without encountering a C family language.
- I agree that it is unfortunate that it uses “?” in particular, since we’d prefer that to be associated with optionals.
The closest proposal I’ve seen is the “if cond then value1 else value2” syntax, however that has serious (IMO) problems:
- It is substantially more verbose than ?:, so much so that it obscures the logic that was trying to be captured. Simple things like this become swallowed in syntax:
let x = cond ? 4 : 8
let x = if cond then 4 else 8
- Because it looks like an if statement, people will end up writing it like:
let x = if cond then
some_long_expression
else
some_other_long_expression
When this happens, we now have new problems:
- At a glance, it “looks” like an if statement, but it is semantically different.
- it only accepts expressions, not statements. The way it is flowed makes it look like a statement.
- It is now force indenting a lot, which just looks weird and isn’t precedented in Swift.
On this thread, people have been focusing on the negative parts of ?: without considering the positive aspects of it. Here are some of the positive aspects of it:
- It is extremely concise, and covers a very common pattern.
- It is pervasively standardized in a very wide range of languages.
- It’s weird syntax reduces the odds that people would flow it out and use very large expressions in it.
- It chains well for multiple conditions because of its associativity.
To repeat what I said upthread, to build a compelling case that we should replace ?:, its replacement should be *better* than ?:.
Believe it or not, we only change things when there are strong reasons, and in the absence of any other strong reason, being similar to the C family is a benefit, not a problem.
-Chris
More information about the swift-evolution
mailing list