user4487951
user4487951

Reputation:

Check if number matches from 1 number to another in switch statement

I have a switch statement comparing an integer. What I'm trying to do, is to check if the integer matches 1 number all the way, up until the next.

For Example: If I want to compare a integer called myInteger, and I want to see, if the numbers 2, 3, 4, 5, or 6 matches `myInteger, then do the following.

Here is a coded example:

switch (myInteger) {
    case 0:
        ...
    case 1:
        ...
    case 2 to 7:    // This is what I'm trying to achieve
        ...
}

So, how can I make the switch statement, iterate over a range of numbers?

Upvotes: 0

Views: 286

Answers (2)

Rory McKinnel
Rory McKinnel

Reputation: 8014

You can actually do this with objective C using the ... operator.

As per your example this would find between 0 and 7 and between 8 and 14. Anything bigger is default action.

switch (myInteger) {
    case 0 ... 7:
      break;
    case 8 ... 14:
      break;
    default:
      break;
}

Try it for yourself and you'll see it works. Its a hangover from gcc support:

Switch-Case Statement and Range of Numbers

Upvotes: 3

Chase
Chase

Reputation: 2304

C-based languages like Objective-C don't support that sort of syntax. Just use an if statement:

if (myInteger >= 2 && myInteger <= 7)) {
    // do stuff
}

In a switch statement, each case value must be a discrete constant.

Upvotes: -1

Related Questions