Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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;
}
like image 570
NoobDev4iPhone Avatar asked Dec 04 '22 04:12

NoobDev4iPhone


1 Answers

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;
}
like image 171
highlycaffeinated Avatar answered May 21 '23 01:05

highlycaffeinated