[swift-evolution] ternary operator ?: suggestion

Al Skipp al_skipp at fastmail.fm
Sat Dec 12 14:23:06 CST 2015


> On 12 Dec 2015, at 19:33, J. Cheyo Jimenez <cheyo at masters3d.com> wrote:
> 
> There are a couple of languages that use then inside their switches. 
> http://rigaux.org/language-study/syntax-across-languages.html#CntrFlowMltSlcSwt <http://rigaux.org/language-study/syntax-across-languages.html#CntrFlowMltSlcSwt>
> 
> I like using only one then in the switch to signal to the parser that this is a switch expression
> 
> The only issue I see is that the colon in the switch is used in the same way as the current ternary expression.  

Good point. This probably makes more sense:

let y = switch c {
  .Red then 1
  .Green then 2
  .Blue then 3
}

> Personally I don't think that a switch expression is all that useful since being a multiline statement actually helps the readability. 

I think it can cut down on unnecessary boilerplate code, especially in functions that contain pattern matching and return a value. In which case you need to declare a variable, do the switch, assign to the var, then return at the end. It’s possible to do the trick with wrapping the switch in a closure inside the function, but that’s also quite ugly. It’d be nice to be able to do:

func f(c: Col) -> Int {
  return switch c {
    .Red then 1
    .Green then 2
    .Blue then 3
  }
}


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


More information about the swift-evolution mailing list