Ternary operator for Switch

After some thought ... is this not the same behavior you are looking for?

let x = [Size.small: 10, .medium: 20, .large: 30][a] ?? 0

I don’t have a computer to test the validity of the code in swift 4 but I believe it should behave the same are your ternary suggestion.

I like that. It can be very useful for nice-looking compute kernels.

kernel func elementwiseSum(_ x: [Float], _ y: [Float], 
                           count: Int32, stride: Int32) -> [Float] {
  return for i in stride(from: 0, to: count, by: stride) {
    yield x[i] + y[i]
  }
}

Sorry for being off topic.

Yeah, I wanted to suggest the same, but it was already mentioned above by Ben Cohen. Together with the type annotation shorthand I think it’s so close to the proposed syntax that it’s not worth improving on.

This almost works but for two large exceptions:

  1. Switch/case statements use pattern matching (which is what I was suggesting in the syntax) as opposed to equality checks. They happen to be the same in the example, but they wouldn't always.

  2. In my suggestion, the order would matter (just like a switch statement), whereas a dictionary has undefined order and doesn't allow overlap.

1 Like
let x = [.small: 10][a] ?? [.medium: 20][a] ?? [.large: 30][a] ?? 0

This is my solution to giving it an order. It makes me laugh.

You can also use the optional default argument in the Dictionary subscript:

let x = [Size.small: 10, .medium: 20, .large: 30][a, default: 0]
3 Likes

Hah, this has turned into pretty creative session! Reminds me of the fun I had looking for Python style conditional expression in Swift:snake::grimacing: