表达式不是iOS目标c中的整数常量表达式

时间:2015-06-29 15:26:16

标签: ios objective-c switch-statement

我想使用以下表达式

-(void)SwitchCondn{
    int expression;
    int match1=0;
    int match2=1;

    switch (expression)

    {
        case match1:

            //statements

            break;

        case match2:

            //statements

            break;

        default:

           // statements

            break;

    }

但我得到了

enter image description here

当我研究时,我找到了

In order to work in Objective-C, you should define your constant either like this:
#define TXT_NAME 1
Or even better, like this:
enum {TXT_NAME = 1};

我一直在使用这种方法。现在我的变量值将在运行时改变,所以我需要以其他方式定义,我不想使用if else所以是否有任何方式的声明变量其他方式

我接受过

的研究

Why can I not use my constant in the switch - case statement in Objective-C ? [error = Expression is not an integer constant expression]

Objective C switch statements and named integer constants

Objective C global constants with case/switch

integer constant does 'not reduce to an integer'

2 个答案:

答案 0 :(得分:10)

错误expression is not an integer constant expression意味着它所说的内容:在case中,值必须是常量,而不是变量。

您可以将switch上方的声明更改为常量:

const int match1=0;
const int match2=1;

或者您可以使用枚举。或#define。但是你不能在那里使用非常数变量。

答案 1 :(得分:6)

如果您想要标记案例,则需要ENUM类型

typedef NS_ENUM(int, MyEnum) {
  match1 = 0,
  match2 = 1
};

- (void)switchCondn:(MyEnum)expression {

  switch (expression)
  {
    case match1:
      //statements
      break;

    case match2:
      //statements
      break;

    default:
      // statements
      break;
  }
}