8

为什么这不起作用:

NSInteger sectionLocation = 0;
NSInteger sectionTitles = 1;
NSInteger sectionNotifications = 2;

switch (section) {
    case sectionLocation:
        //
        break;
    case sectionTitles:
        //
        break;
    case sectionNotifications:
        // 
        break;
    default:
        //
}

我得到这个编译错误:

错误:案例标签不会减少为整数常量

不能像这样使用NSInteger吗?如果是这样,是否有另一种方法可以在 switch 语句中使用变量作为案例?sectionLocation等具有可变值。

4

5 回答 5

11

问题不在于标量类型,而是案例标签在像这样的变量时可能会改变值。

出于所有意图和目的,编译器将 switch 语句编译为一组 goto。标签不能是可变的。

使用枚举类型或#defines。

于 2011-01-08T19:13:47.863 回答
4

原因是编译器经常希望使用开关值作为进入该表的键来创建一个“跳转表”,并且只有在它打开一个简单的整数值时才能这样做。这应该起作用:

#define sectionLocation  0
#define sectionTitles  1
#define sectionNotifications 2

int intSection = section;

switch (intSection) {
    case sectionLocation:
        //
        break;
    case sectionTitles:
        //
        break;
    case sectionNotifications:
        // 
        break;
    default:
        //
}
于 2011-01-08T19:14:42.050 回答
2

这里的问题是您正在使用变量。您只能在 switch 语句中使用常量。

做类似的事情

#define SOME_VALUE 1

或者

enum Values {
    valuea = 1,
    valueb = 2,
    ...
}

您将能够在 switch 语句中使用 valuea 等。

于 2011-01-08T19:12:17.167 回答
1

如果您的案例值在运行时确实发生了变化,那么这就是 if...else if...else if 构造的用途。

于 2011-01-08T19:25:32.810 回答
-2

或者只是这样做

switch((int)secion)
于 2011-01-09T00:05:40.420 回答