[swift-evolution] ternary operator ?: suggestion
Sean Heber
sean at fifthace.com
Tue Jan 5 10:23:25 CST 2016
> 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.
l8r
Sean
More information about the swift-evolution
mailing list