Hacker News new | past | comments | ask | show | jobs | submit login

I tend to avoid using switch/case for quite irrational reasons. The break statement just looks wrong and I can't layout the code in a way I find at all pleasing. I'll almost always use a sequence of else if conditions instead.

In my ideal world, it'd look like...

    switch (x)
    {
        case 1:
        {
            /* ... */
        }
        case 2:
        case 3:
        {
            /* ... */
        }
    }
And before anyone points it out, switch is the same as else if when the thing being compared is a simple local variable.



Most of the time when I use switches, I'm returning from inside the case, because I tend to pull the switch out into another function.

It's usually a good idea to create a new scope with your cases, so you can avoid some irritating variable name clashes, since, unlike and if, switch cases don't automatically do that, i.e.

  switch(foo) {
    case 0:
      var bar = 2;
      // do stuff...
      break;
    case 1:
      var bar = 47; // error, conflicting variable name
      // do stuff...
      break;
  }


Same here, plus I think the parent brakes are noise, can the compiler just know that the switch statement ends on last case?


No, as in some instances you may wish to do the same thing for two case statements, so you need it to fall through case1 into case2.

In other situations, you really don't want it to do that, so a break is required.

How would the compiler know the difference? Note that you can't "fall through" cases in Swift, and it is irritating. It stops you using the same code for two case statements - you have to duplicate it or put it into a function.


Not with nested switch statements.


...I don't want to ever have to work with your code.


But you can already do almost that, right?

    switch (x)
    {
        case 1:
        {
            /* ... */
        }
        break;
        case 2:
        case 3:
        {
            /* ... */
        }
        break;
    }


The problem is "falling through" the case statements. You can do this in C++ and C, which is really useful. You can't do this in Swift, and it's incredibly annoying.

Break is there for a good reason.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: