[swift-evolution] ternary operator ?: suggestion

Al Skipp al_skipp at fastmail.fm
Sat Dec 12 13:15:01 CST 2015


> On 12 Dec 2015, at 14:48, Paul Ossenbruggen <possen at gmail.com> wrote:
> 
> Dropping “case” might be interesting, since it becomes a little redundant in the “switch” situation, this is one advantage of having a new keyword, but not sure this reads as well:
> 
> let v = switch val then .Red: 1, .Green: 2, .Blue: 3
> 
> It is definitely nice in it’s compactness which is a big plus. 
> 
> Another possibility, because “switch" does not need to resolve the syntactic ambiguity, but then we lose the “then” always meaning an expression consistency. 
> 
> let v = switch val case .Red: 1, case .Green: 2, case .Blue: 3
> 
> this might be better for switch because we don’t need to mix “then” with “switch” which historically has not been done. Question is, is it better to go with “then” as expression consistency or with slightly more compact and following the conventions out there. Personally, I am not bothered by using “then” with “switch” 

Would the cases need to be comma separated? Would a new line make more sense instead?

Currently this is possible:

enum Col { case Red, Green, Blue }

let c = Col.Blue

let x: Int = {
  switch c {
  case .Red: return 1
  case .Green: return 2
  case .Blue: return 3
  }
}()

It works, but there are several things I don’t like:
- the switch statement must be wrapped in a closure which is invoked at the end.
- the type of ‘x’ needs to be given
- each case requires a return statement 

Here’s a proposal for a switch expression:

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

I think the braces are probably needed in the switch expression, also the ‘then’ keyword’ does look a bit peculiar. Any other ideas on how to support both switch statements and expressions?

Al


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


More information about the swift-evolution mailing list