user-44651
user-44651

Reputation: 4124

Use variables as case constants in swich statement

I'm trying to use a variable as the case match, however I get "Expression is not an integer in Objective-C.

Is it possible to use variable in switches in this manner?

  int count = [array count];

    switch ([number to check]) {
        case 0:
            //first statement
            break;
        case 1 ... (count -1):
           //somewhere between 1 and the next to last statement
           //Basically the middle
            break;
        case count:
            //Last statement

        default:
            break;
    }

Upvotes: 2

Views: 59

Answers (2)

TwoStraws
TwoStraws

Reputation: 13127

Objective-C's switch statement does support ranges of values as you've seen, but doesn't support variable matches I'm afraid.

So, the below code is valid because I've used exact integers:

int numberOfKittens = 12;
NSString *kittenDescription;

switch (numberOfKittens) {
    case 0 ... 5:
        kittenDescription = @"Need more kittens";
        break;

    case 6 ... 10:
        kittenDescription = @"That's a good number of kittens.";
        break;

    case 11 ... 20:
        kittenDescription = @"Are you sure you can handle that many kittens?";
        break;

    default:
        kittenDescription = @"You must really love kittens!";
}

…but trying to put a variable in place of any of those will fail.

If this is something you desperately want, consider using Swift because it has a much more expressive switch matching system. Here's that same code in Swift, now with a variable being used to match a case:

let upperLimit = 20
let numberOfKittens = 19
var kittenDescription = ""

switch (numberOfKittens) {
case 0 ... 5:
    kittenDescription = "Need more kittens"

case 6 ... 10:
    kittenDescription = "That's a good number of kittens."

case 11 ... upperLimit:
    kittenDescription = "Are you sure you can handle that many kittens?"

default:
    kittenDescription = "You must really love kittens!"
}

Upvotes: 2

rmaddy
rmaddy

Reputation: 318944

Objective-C (and C) switch only supports a single primitive constant value for each case statement (or a range as pointed out in the answer by TwoStraws). You would be much better off writing your code using if/else:

if ([number to check] == 0) {
} else if ([number to check] >= 1 && [number to check] < count) {
} else if ([number to check] == count) {
} else {
}

Upvotes: 2

Related Questions