[swift-evolution] ternary operator ?: suggestion

David Waite david at alkaline-solutions.com
Wed Dec 23 01:22:07 CST 2015


In the case where your input is hashable, you could just do:

let i = [.Red:0xff0000, .Green:0x00ff00, .Blue:0x0000ff][color]

this would mean that color must be a Color and not an Optional<Color> (because of swift 2.x limitations)

-DW

> On Dec 22, 2015, at 8:04 AM, Félix Cloutier via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I like the gist of it too, though you seem to introduce both a new keyword and a new syntax. (To be clear, I like the syntax but I'm ambivalent towards reusing switch instead of which.)
> 
> My minor suggestions would to avoid braces for things that aren't scopes; that either the comma or the the question mark is redundant in their current position (you need a start delimiter or an end delimiter but you don't need both); and that it needs a way to handle a default case if enumeration isn't exhaustive (I'd do that by returning an optional).
> 
>> let i = which color (.Red: 0xff0000, .Green: 0x00ff00, .Blue: 0x0000ff) ?? 0x000000
> 
> 
> Thinking out loud, once you remove the question marks it really looks like a dictionary literal, so maybe it could even use square brackets to close the gap.
> 
>> let i = which color [.Red: 0xff0000, .Green: 0x00ff00, .Blue: 0x0000ff] ?? 0x000000
> 
> 
> I thought about subscripting a dictionary literal in place:
> 
>> [Color.Red: 0xff0000, ...][color] ?? 0x000000
> 
> 
> but that won't support elaborate pattern matching, and I think that this is a deal breaker for the functional folks.
> 
> Félix
> 
>> Le 22 déc. 2015 à 09:31:32, Charles Constant <charles at charlesism.com> a écrit :
>> 
>> Just goofing on this a little. What if we called it a "which" statement, instead of a "switch" statement? It's a bit cutesy, but not too verbose, and it makes sense if you read it aloud.
>> 
>> let i = which color {
>> 	? .Red: 0xFF0000, 
>> 	? .Green: 0x00FF00, 
>> 	? .Blue: 0x00000FF
>> }
>> 
>> let i = which boo {
>> 	? true: 1, 
>> 	? false: 0, 
>> 	? nil: -1
>> }
>> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list