1

I have following code

NSString * myStr = [[NSString alloc] initWithFormat:@""];

But in Xcode I have red exclamation with "Expected expression".

I have solved problem with:

[NSString stringWithFormat:@"Number is not from 1 to 6. randomNumber is %d", randomNumber]

But I want to know what is the problem.

Image http://imgur.com/iICMhYc&S7QwhFT#1enter image description here

Thanks

Fry
  • 6,235
  • 8
  • 54
  • 93
WebOrCode
  • 6,852
  • 9
  • 43
  • 70

3 Answers3

6

In according to the Objective-C rules, if you declare an object inside a case of a switch you have to surround all the case body with brackets {}.

switch(randomNumber){
   case 1:{
      break;
   }
   default:{
      NSString * myStr = [[NSString alloc] initWithFormat:@""];
      break;
   }
}
Fry
  • 6,235
  • 8
  • 54
  • 93
  • This doesn't really answer the question being asked, chances are OP had a syntax error above or below this line and Xcode placed the error on it. – Tim Mar 28 '14 at 10:55
  • So if I understand you correctly. I have putted {} inside the default and the error is gone. So that was the problem. Any explanation why ? – WebOrCode Mar 28 '14 at 11:21
  • Read [Declaring variables inside a switch statement](http://stackoverflow.com/questions/1231198/declaring-variables-inside-a-switch-statement) The problem is that `case` is a label and according with the language rules you can't put a declaration as first line of a label. – Fry Mar 28 '14 at 11:24
  • This is exactly what I was after! Without it, it seems to to confuse the syntax parser :D – cwiggo May 13 '15 at 11:04
1

try this:

 default:{
       NSString * myStr = [[NSString alloc] initWithFormat:@""];
       break;
    }

same with case, if you want define instance in switch, add {...}

simalone
  • 2,768
  • 1
  • 15
  • 20
1

You can't declare a variable in a switch statement unless you enclose the case/default body in {}.

Note that the reason for this is that a switch is one long block of code and the variable appears to be declared within it, but may not be initialized along all possible paths. You'd get the same error if you declared a variable after a label that is the target of a goto (and note that a switch is just a formalized goto-label setup).

Hot Licks
  • 47,103
  • 17
  • 93
  • 151