NoobDev4iPhone
NoobDev4iPhone

Reputation: 5739

"Statement requires expression of integer type" error with switch statement and array of strings

Trying to work with array, but it gives me "Statement requires expression of integer type('id' invalid)" right at switch statement. What's wrong?

NSArray count = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];    

switch ([count objectAtIndex: myIndex]) {
    case 1:
        NSLog(@"One");
        break;
    case 2:
        NSLog(@"Two");
        break;
    case 3:
        NSLog(@"Three");
        break;
    default:
        break;
}

Upvotes: 4

Views: 17910

Answers (4)

bryanmac
bryanmac

Reputation: 39306

You are creating an array of literal NSStrings and doing case statements on ints. You can only switch on integral types.

The problem is arrayWithObjects creates an array of NSObject derived objects which you can't switch on an object (id).

If you want to store an array of numbers, then one option is to store NSNumber objects rather than relying on the fragility of storing strings that you hope are numbers. This works:

NSArray *arr = [NSArray arrayWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];

switch ([[arr objectAtIndex:1] intValue]) {
    case 1:
        NSLog(@"1");
        break;

    case 2:
        NSLog(@"2");
        break;

    default:
        break;
}

It outputs:

2012-03-05 23:23:46.798 Craplet[82357:707] 2

Upvotes: 3

highlycaffeinated
highlycaffeinated

Reputation: 19867

A switch statement only works on integral types. Your array contains NSString objects. Convert the NSString that you get from the array to an integer like this:

NSArray count = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];

NSString *obj = [count objectAtIndex: myIndex];
switch ([obj intValue]) {
    case 1:
        NSLog(@"One");
        break;
    case 2:
        NSLog(@"Two");
        break;
    case 3:
        NSLog(@"Three");
        break;
    default:
        break;
}

Upvotes: 14

QED
QED

Reputation: 9933

Your array objects are NSStrings, not ints. What is the larger picture here that you're trying to accomplish?

You could:

NSString *str = [count objectAtIndex:myIndex];
if ([str isEqualToString:@"1"]) NSLog(@"One");
else if ... // etc

Better yet:

static NSString *one = @"1";
static NSString *two = @"2";
// etc

NSArray *count = [NSArray arrayWithObjects:one, two, ... nil];

NSString *str = [count objectAtIndex:myIndex];

if (str == one) NSLog(@"One"); // this works because now 'str' and 'one' are the same object
else if ... // etc

Upvotes: 1

superfell
superfell

Reputation: 19050

[count objectAtIndex:] returns an Id (aka object), which in your particular case would be a NSString, in either case, its not an int that your case expression is expecting. You'll want [[count objectAtIndex:myIndex] intValue] to convert the NSString to an integer.

Upvotes: 1

Related Questions