【问题标题】:Objective-C Switch Statement [duplicate]Objective-C Switch 语句 [重复]
【发布时间】:2011-12-22 14:56:08
【问题描述】:

可能重复:
Declaring variables inside a switch statement

我很难让 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;
    }

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

【问题讨论】:

    标签: objective-c ios switch-statement


    【解决方案1】:

    标签后不能添加变量声明。例如,您可以添加分号而不是调用NSLog()。或者在 switch 之前声明变量。或者添加另一个{}

    【讨论】:

    • 最简单的方法是在 case 和 declaration 之间加上分号。
    • 是的,它肯定是最少的击键次数,但根据上下文,最美观的解决方案可能会有所不同:)
    • 这就是为什么我投票赞成你的答案:)
    • 我在这里说:谢谢 ;-)
    • 有趣,感谢您的提示。牙套可能在美学上是最好的。
    【解决方案2】:

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

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

    试试这个...

    【讨论】:

    • 看来你可以——我不明白为什么不能。在 switch 语句的第二行,声明有效。即使第一行只是';'
    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多