Objective-C Switch 语句
可能的重复:
在 switch 语句内声明变量
我很难让 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;
}
我看不到语法错误,就好像我需要欺骗编译器允许这样做。
Possible Duplicate:
Declaring variables inside a switch statement
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不能在标签后添加变量声明。例如,您可以添加分号而不是调用
NSLog()
。或者在开关之前声明变量。或者添加另一个{}
。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{}
.删除 switch 语句中的变量声明部分。
在 switch 语句中,您不能在 Objective-C 中创建任何变量。
试试这个...
Remove the variable declaration part within the switch statement.
Within switch statement you can't create any variable in Objective-C.
Try this...