[swift-evolution] ternary operator ?: suggestion
matthew at anandabits.com
Tue Jan 5 10:29:30 CST 2016
> 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. If you want to make this more like ternary we should just allow `:` without any keyword for the default clause.
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.
More information about the swift-evolution