aednichols aednichols - 6 months ago 49
Objective-C Question

Defining a block in a switch statement results in a compiler error

Consider the following switch statement:

switch (buttonIndex) {
case 0:
[self fooWithCompletion:^{
[weakSelf finishEditing];
}];
break;
case 1: // Error here
[self barWithCompletion:^{
[weakSelf finishEditing];
}];
break;
default:
break;
}


It causes the compiler error

Cannot jump from switch statement to this case label


on the line
case 1:
.

Why is this happening and how do I fix it?

Answer

The block definition creates a new scope which seems to interfere with the compiler's ability to correctly interpret the switch statement.

Adding scope delimiters for each case label resolves the error. I think this is because the block's scope is now unambiguously a child of the case scope.

switch (buttonIndex) {
    case 0:
    {
        [self updateUserDataWithCompletion:^{
            [weakSelf finishEditing];
        }];
        break;
    }
    case 1:
    {
        [self updateOtherDataWithCompletion:^{
            [weakSelf finishEditing];
        }];
        break;
    }
    default:
        break;
}

There's a bug open with LLVM for a similar issue.

Comments