Expression is not an integer constant expression in iOS objective c

此生再无相见时 提交于 2021-01-02 07:53:56

问题


I want to use the following expression

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

    switch (expression)

    {
        case match1:

            //statements

            break;

        case match2:

            //statements

            break;

        default:

           // statements

            break;

    }

But I got

enter image description here

When I research I found

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

I have been using this methods since long time . Now my variable value will change in run time so I need to define in others way and i didn't want to use if else so is there any way of declaration variable others way

I have had study following

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'


回答1:


The error expression is not an integer constant expression means just what it says: in a case, the value must be constant, as in, not a variable.

You could change the declarations above the switch to be constants:

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

Or you could use an enumeration. Or a #define. But you can't use non-constant variables there.




回答2:


If you want to have labeled cases, you need a ENUM type

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


来源:https://stackoverflow.com/questions/31119606/expression-is-not-an-integer-constant-expression-in-ios-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!