ios Objective-C Switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8605619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C Switch Statement
提问by Echilon
Possible Duplicate:
Declaring variables inside a switch statement
可能的重复:
在 switch 语句中声明变量
I'm having difficulty getting XCode to let me write a particular switch statement in Objective-C. I'm famiiar with the syntax and could rewrite it as if/else blocks but I'm curious.
我很难让 XCode 允许我在 Objective-C 中编写特定的 switch 语句。我熟悉语法,可以将它重写为 if/else 块,但我很好奇。
switch (textField.tag) {
case kComment:
ingredient.comment = textField.text;
break;
case kQuantity:
NSLog(@""); // removing this line causes a compiler error
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
fmt.generatesDecimalNumbers = true;
NSNumber *quantity = [fmt numberFromString:textField.text];
[fmt release];
ingredient.quantity = quantity;
break;
}
I can't see the syntax error, it's as though I need to trick the compiler into allowing this.
我看不到语法错误,就好像我需要欺骗编译器允许这样做一样。
回答by Michael Krelin - hacker
You can not add variable declaration after the label. You can add a semicolon instead of call to NSLog()
for instance. Or declare variable before the switch. Or add another {}
.
不能在标签后添加变量声明。例如,您可以添加分号而不是调用NSLog()
。或者在 switch 之前声明变量。或添加另一个{}
.
回答by iCreative
Remove the variable declaration part within the switch statement.
删除 switch 语句中的变量声明部分。
Within switch statement you can't create any variable in Objective-C.
在 switch 语句中,你不能在 Objective-C 中创建任何变量。
NSNumberFormatter *fmt = nil;
NSNumber *quantity = nil;
switch (textField.tag) {
case kComment:
ingredient.comment = textField.text;
break;
case kQuantity:
fmt = [[NSNumberFormatter alloc] init];
fmt.generatesDecimalNumbers = true;
quantity = [fmt numberFromString:textField.text];
[fmt release];
ingredient.quantity = quantity;
break;
}
Try this...
尝试这个...