[Idea] Switch without subject

Hi,

For a couple times now, I found myself missing a nice syntax to do pattern matching on multiple unrelated subjects (with exclusion).

Given four conditions and/or pattern matching named cond1, cond2, cond3, cond4, I'd like to avoid :

if cond1 {
  // do1
} else if cond2 {
  // do2
} else if cond3 {
  // do3
} else if cond4 {
  // do4
}

or

switch (cond1, cond2, cond3, cond4) {
case (true, _, _, _): // do1
case (_, true, _, _): // do2
case (_, _, true, _): // do3
case (_, _, _, true): // do4
default: fatalError()
}

but do this:

switch {
case cond1: // do 1
case cond2: // do 2
case cond3: // do 3
case cond4: // do 4
}

Obviously the gain increase (well I think it does) the more statements there are.
One case where I found the if else dance particularly clunky is when defining the body of a SwiftUI view.

Credit goes directly to Kotlin and its when statement and I must say I'm quite surprised the subject hasn't been discussed already on this forum.

Sadly I'm no compiler developer so this is only an idea / prepitch that I would love someone to take on.

7 Likes

We can currently do

switch true {
case cond1: // do 1
case cond2: // do 2
case cond3: // do 3
case cond4: // do 4
}

which is just a true away from Koltin's argument-less when expression.

8 Likes

I was pretty sure I tried this, kinda explain why there was no discussion about it.
Thanks !

That still needs a default case for if none of the cases evaluate to true, doesn’t it? (Even if it is just default: break to do nothing.)

2 Likes
Terms of Service

Privacy Policy

Cookie Policy