Small things often cause pain – So why can’t I create a variable inside a switch statement?

Sometimes the smallest things can cause you pain. I had a nice example of this today. I’m still new to Objective C and find something new everyday. Was using a switch statement and had what at the time seemed like an odd little issue. I couldn’t seem to create variables and call methods. The error message I was getting back really wasn’t that helpful. Turns out it was as simple as surrounding the case statement calls in curly brackets. See below:

Fails:

case 2: 
    Alert *alert = [allAlerts objectAtIndex:indexPath.row];

    alertCell.textLabel.text = alert.date;//@"Date";
    alertCell.detailTextLabel.text = @"Alert Message";
    return alertCell;
 break;

Works:

case 2: {
    Alert *alert = [allAlerts objectAtIndex:indexPath.row];

    alertCell.textLabel.text = alert.date;//@"Date";
    alertCell.detailTextLabel.text = @"Alert Message";
    return alertCell;
} break;
http://stackoverflow.com/questions/4902568/how-do-i-create-a-variable-inside-a-switch-statement-for-a-uitableview

Yup all I need was those two curly brackets 😉 Now if only Xcode could have told me that!  Yeah I know this isn’t a big thing, just think it’s funny how the small things can be such a pain at times and how knowing the syntax of a language really can be an advantage at times. I guess the moral of the story is that small things really do matter.