DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
val_baca profile image
Valentin Baca

Swift's switch is the only one that I think gets it right. It provides enough simplicity and usability to warrant use over if-else chains.

From docs.swift.org/swift-book/Language...

  • compund cases case "a", "A":
  • interval matching case 1..<5:
  • tuples switch point: case (0, 0)
  • value binding case let(x, y)
  • where checks
  • explicit fallthrough

Granted, each of these can still be done with if-else, I like the convenience of it all.

Collapse
 
jeikabu profile image
jeikabu • Edited

This here. switch in some languages (like F#, rust, and apparently swift- amongst others) has additional "powers".

In C# 8 you can also use it as an expression:

return x switch {
  0: something,
  // More
  _: whatever,
};

Otherwise it's main advantage is clarity for large numbers of options and optional fall through (double-edged sword that it is).

if (x == 0) {
  return something;
} else if (x == 1) {
// 10 more cases
else {
  return whatever;
}

// vs
switch (x) {
  case 0: return something;
  // 10 more
  default: return whatever;
}

Regardless what you do with your brackets/whitespace, the switch logic is clearly only about the value of x.

Also, historically compilers were more likely to turn it into a jump table rather than chain of branches.