4

Sometimes Xcode will show an error "Expected expression" on the line after a case. For example, Xcode is pointing to UserContentViewController with a red arrow:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case IndexVideo: 
            UserContentViewController* detailViewController = [[UserContentViewController alloc] initWithUser:self.user];
            [self.navigationController pushViewController:detailViewController animated:YES];
            break;

    }
}

If I put braces around my case, the error is gone. Firstly, I want to know what is the problem with not using braces. I've never used braces in cases in any other language. Secondly, why does Xcode only complain about my cases on rare occasions? I can't quite discern what type of code triggers this error.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Pwner
  • 3,714
  • 6
  • 41
  • 67
  • possible duplicate of [Why can't variables be declared in a switch statement?](http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement) or [Can I declare variables inside an Objective-C switch statement?](http://stackoverflow.com/questions/1115304/can-i-declare-variables-inside-an-objective-c-switch-statement) or [Declaring variables inside a switch statement](http://stackoverflow.com/questions/1231198/declaring-variables-inside-a-switch-statement). Just to name three ;-) – Matthias Bauch Jul 10 '13 at 22:39

1 Answers1

14

Basically, if you want to declare a variable you need to add the braces to define scope.

ARC also adds some requirements (or, rather, stricter requirements) to define scope (so you may get a number of "switch case is in protected scope" errors to fix when upgrading an older codebase). This is because ARC needs to know in detail when a variable isn't / can't be referred to any more so that it can deal with the release correctly.

Everything relates back to giving the compiler enough information about the scope of declared variables. Should they be part of a single case, or multiple cases...

Wain
  • 118,658
  • 15
  • 128
  • 151