by billpg · 10y ago · 0 comments
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.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;
}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.
switch (x)
{
case 1:
{
/* ... */
}
break;
case 2:
case 3:
{
/* ... */
}
break;
}Break is there for a good reason.