I seem to be having a problem creating new local variables inside a switch statement. I thought it was something in my class headers, but was even getting errors trying to allocate a new NSObject. Here's my syntax:
-(NSArray *)charactersFromChapter:(NSInteger)number {
NSObject *noError = [[NSObject alloc] init];
//line above does not cause error
NSArray *characters;
switch (number) {
case 1:
NSObject *obj = [[NSObject alloc] init];
//error happens in line above (Expected expression)
characters = [NSArray arrayWithObject:obj];
break;
case 2:
break;
case 3:
break;
}
return characters;
}
Syntax. The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Variables are not allowed. The default statement is optional and can appear anywhere inside the switch block.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
In a switch statement, you cannot initialize variables without setting a scope first, so to fix it, do something like this:
switch (some_expression) {
case case_1:
{ // notice the brackets
id some_obj = [MyObj new];
break;
}
default:
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With