[swift-evolution] ternary operator ?: suggestion
Thorsten Seitz
tseitz42 at icloud.com
Tue Jan 5 11:05:31 CST 2016
> Am 05.01.2016 um 17:29 schrieb Matthew Johnson <matthew at anandabits.com>:
>
>
>> On Jan 5, 2016, at 10:23 AM, Sean Heber <sean at fifthace.com> wrote:
>>
>>
>>> On Jan 5, 2016, at 12:29 AM, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>> I once suggested the following ternary like switch:
>>>
>>> let x = color ?
>>> case .Red: 0xFF0000
>>> case .Green: 0x00FF00
>>> case .Blue: 0x0000FF
>>> default: 0xFFFFFF
>>
>> This is my favorite and addresses the sort of situations I’ve run into where using a switch statement seems unnecessarily bulky. I’d like to see this as a proposal because it’d be a very useful construct on its own.
>>
>> Using “else” would be maybe a little odd when paired with cases, but it also doesn’t look bad and, I think, could be argued that it makes sense in the context of an expression:
>>
>> let x = color ?
>> case .Red: 0xFF0000
>> case .Green: 0x00FF00
>> case .Blue: 0x0000FF
>> else: 0xFFFFFF
>>
>> Then you could say this when using a boolean:
>>
>> let x = something ? case true: thing() else: otherThing()
>>
>> And maybe allow a special case for boolean where you can leave off the “case true:” part:
>>
>> let x = something ? thing() else: otherThing()
>>
>> And then you could more or less replace ternary with this new construct that can do even more while looking very similar and still being pretty terse and the addition of “else” in there makes the entire expression stand out a bit more than traditional ternary expressions which, I think, addresses one of the complaints there.
>
> I do not like this idea. I think a case expression should follow the case statement where a corresponding keyword is used.
That's what I am thinking as well. Keep the similarities with the corresponding statement as much as possible otherwise the result will be confusing.
> If you want to make this more like ternary we should just allow `:` without any keyword for the default clause.
No, please. As I just said, keep the similarities with the corresponding statement as close as possible.
> Your suggestion that this would replace ternary and require an `else:` instead of `:` is going to be a non-starter. You may want to read the “frequently proposed changes” document as it explains why such a change won’t happen.
I'd prefe to keep the ternary as most compact form of a conditional instead of watering down the switch-expression. Too confusing IMO.
-Thorsten
More information about the swift-evolution
mailing list