Renata
Renata

Reputation: 203

ios there is a way to combined switch cases?

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

Upvotes: 11

Views: 4912

Answers (3)

Darius Miliauskas
Darius Miliauskas

Reputation: 3514

It is also possible to use ranges (a little bit less code). The following example illustrates it:

switch (value)
   {
      case 0 ... 2:
         NSLog (@"0,1,2 cases");
         break
      case 3:
         NSLog (@"3 cases");
         break;
      default:
         NSLog (@"anything else");
         break;
   }

Upvotes: 0

JP Illanes
JP Illanes

Reputation: 3675

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.

Upvotes: 30

Ashok
Ashok

Reputation: 6244

Alternatively, you can do this...

case 0:
case 1:
case 2:
    NSLog();
    break;

case 3:
   NSLog()
   break;

default:
   NSLog();
   break;

Upvotes: 1

Related Questions