Could you try those two codes ? The first one raises an error, not the second one. I'd like to know if it's because of my XCode version, and if not, why is it happening.
int typeNumber = 4;
switch (typeNumber) {
case typeNumberEvent:
NSString myString;
break;
case typeNumberAd:
NSURL myURL;
break;
default:
NSNumber myNumber;
开发者_开发技巧 break;
}
int typeNumber = 4;
switch (typeNumber) {
case typeNumberEvent:
NSLog(@"hello");
NSString myString;
break;
case typeNumberAd:
NSLog(@"hello");
NSURL myURL;
break;
default:
NSLog(@"hello");
NSNumber myNumber;
break;
}
The compiler throws error if you try to create a variable at the first line of case
.
Just enclose the case block with braces. Everything will be alright.
case typeNumberEvent: {
NSString myString;
break;
}
If you declare variables inside a case block, you should declare that block with curly braces. Your example would become:
int typeNumber = 4;
switch (typeNumber) {
case typeNumberEvent:
{
NSString myString;
break;
}
case typeNumberAd:
{
NSURL myURL;
break;
}
default:
{
NSNumber myNumber;
break;
}
}
This answer sums it up nicely, too: Can I declare variables inside an Objective-C switch statement?
精彩评论