Objective-C开关语句

10

可能是重复问题:
在switch语句中声明变量

我在使用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;
    }

我看不到语法错误,就好像我需要欺骗编译器允许这样做。

2个回答

15

在标签之后不能添加变量声明。例如可以用分号代替对NSLog()的调用。或者在switch语句之前声明变量。或者添加另一个{}


最简单的方法是在 case 和声明之间加上分号。 - Ariel
是的,这确实是最少按键次数的解决方案,但根据上下文,最美观的解决方案可能会有所不同 :) - Michael Krelin - hacker
这就是为什么我给你的回答点了赞 :) - Ariel
这里是我要说的:谢谢;-) - Michael Krelin - hacker
有趣,谢谢你的提示。花括号可能在美学上最好。 - Echilon
@Echilon,我经常持有同样的观点。 - Michael Krelin - hacker

-2

在 switch 语句中删除变量声明部分。

在 Objective-C 中,不能在 switch 语句中创建任何变量。

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; 
    }

试试这个...


1
在 switch 语句的第二行,似乎可以这样做——我不知道为什么不行。即使第一行只有 ';' 声明也是有效的。 - Jhong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接