10

Possible Duplicate:
Declaring variables inside a switch statement

I'm having difficulty getting XCode to let me write a particular switch statement in Objective-C. I'm famiiar with the syntax and could rewrite it as if/else blocks but I'm curious.

switch (textField.tag) {
        case kComment:
            ingredient.comment = textField.text;
            break;
        case kQuantity:
            NSLog(@""); // removing this line causes a compiler error           
            NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
            fmt.generatesDecimalNumbers = true;
            NSNumber *quantity = [fmt numberFromString:textField.text];
            [fmt release]; 
            ingredient.quantity = quantity;
            break;
    }

I can't see the syntax error, it's as though I need to trick the compiler into allowing this.

Community
  • 1
  • 1
Echilon
  • 10,064
  • 33
  • 131
  • 217

2 Answers2

15

You can not add variable declaration after the label. You can add a semicolon instead of call to NSLog() for instance. Or declare variable before the switch. Or add another {}.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
-2

Remove the variable declaration part within the switch statement.

Within switch statement you can't create any variable in Objective-C.

NSNumberFormatter *fmt = nil;
NSNumber *quantity = nil;
switch (textField.tag) {
        case kComment:
            ingredient.comment = textField.text;
            break;
        case kQuantity:
            fmt = [[NSNumberFormatter alloc] init];
            fmt.generatesDecimalNumbers = true;
            quantity = [fmt numberFromString:textField.text];
            [fmt release]; 
            ingredient.quantity = quantity;
            break; 
    }

Try this...

markhunte
  • 6,805
  • 2
  • 25
  • 44
iCreative
  • 1,499
  • 1
  • 9
  • 22
  • 1
    It appears you can -- and I don't see why not. on the second line in a switch statement, declaration works. Even if the first line is just ';' – Jhong May 07 '12 at 16:12