A switch statement gotcha in Objective-C

If you let XCode's code completion create your switch statement for you, you might run into this little gotcha.

The following code...

NSUInteger i;
switch (i) {
  case 0:
    // Do something
    break;
  default:
    NSString *s = @"something";
    s;
    break;
}

... doesn't compile. Instead, you get the following two errors:

The culprit is the auto-generated code. The following code does compile. Note the curly braces.

NSUInteger i;
switch (i) {
  case 0:
  {
    // Do something
    break;
  }

  default:
  {
    NSString *s = @"something";
    s;
    break;
  }
}

The curly brackets are not required for switch statements but when they are absent, a statement must follow the case or default labels. Declarations are not statements in C and thus result in this error.

The following code, which doesn't use curly braces, also compiles.

NSUInteger i;
switch (i) {
  case 0:
    // Do something
    break;
  default:
    NSLog(@"Magic? Not really, just a statement.");
    NSString *s = @"something";
    s;
    break;
}

Hope this helps you in case you encounter this sneaky little gotcha!

Interested in learning iPhone development? Check out my Introduction to iPhone App Development Course.

Comments