Andrew
Andrew

Reputation: 16051

Quicker way of typing out if statements?

Say i have...

if (value1 == 1 || value1 == 3 || value1 == 6) {
//Things happen
}

Since it's referencing value1 each time, is there a quicker way of doing this?

Upvotes: 0

Views: 89

Answers (3)

Caleb
Caleb

Reputation: 124997

If you mean doing something like:

if (value1 in {1, 3, 6}) ...

then no, you can't do anything like that. Objective-C doesn't have any sort of set operators for basic types. There are other ways to write your code, though, so that you can do a similar operation quickly. For example, if the number of possible values isn't too large, you can use bit positions:

if (value1 & (0x02 | 0x08 | 0x20)) ...

The compiler will probably OR those constants together at compile time, so the whole comparison takes only as long as a bitwise AND operation.

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37517

You can use a switch statement:

   switch (value1)
   {
      case 1:
      case 3:
      case 6:
        //Things happen
        break;
      case 4:
        //Something else happens
        break;
      default:
        //Something else happens
   }

This is useful if you were otherwise going to have a lot of if statements checking the same variable.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

Not really.

An alternative is:

switch (value1)
{
case 1:
case 3:
case 6:
    // Things happen
}

But it's not "quicker"!

Upvotes: 3

Related Questions