I was wondering if there is a way to combined switch cases for example:
switch (value)
{
case 0,1,2:
nslog (@"0,1,2 cases");
break
case 3:
nslog (@"3 cases");
break;
default:
NSLog (@"anything else");
break;
}
I'll really appreciate your help
Whenever you want to combine multiple cases you just need to write a case with case label and colons(:). You can't provide the break statement in between of combined cases.
Unlike C, Swift allows multiple switch cases to consider the same value or values. In fact, the point (0, 0) could match all four of the cases in this example. However, if multiple matches are possible, the first matching case is always used.
In the most basic form of a switch/case you tell Swift what variable you want to check, then provide a list of possible cases for that variable. Swift will find the first case that matches your variable, then run its block of code. When that block finishes, Swift exits the whole switch/case block.
You mean, something like this?
switch (value)
{
case 0:
case 1:
case 2:
NSLog (@"0,1,2 cases");
break;
case 3:
NSLog (@"3 cases");
break;
default:
NSLog (@"anything else");
break;
}
You know, the switch case structure will execute each line inside the braces starting from the corresponding case line, until it reach the last one or a break. So, if you don't include a break after a case, it will go on executing the next case also.
Alternatively, you can do this...
case 0:
case 1:
case 2:
NSLog();
break;
case 3:
NSLog()
break;
default:
NSLog();
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With