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

前端 未结 2 2016
难免孤独
难免孤独 2020-12-18 22:06

So I have an issue with using a constant variable in the following switch statement in Objective-C.

I have Constants.h with the following:



        
相关标签:
2条回答
  • 2020-12-18 22:19

    Quick solution, you should place NSInteger const TXT_NAME = 1; in Constants.h, and don't need anything in Constants.m.

    Reason: If you set the value of the constant in the .m, it is not visible by other translation units that only include the .h file. The value of the constant must be known at compile time to be able to be used in a case within a switch.

    Update:

    The above works when compiling in Objective-C++. You need to have your files end in .mm instead of .m for them to be compiled in Objective-C++ instead of Objective-C.

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

    0 讨论(0)
  • 2020-12-18 22:19

    I would normally follow what Apple seem to do and define a typedef enum in the .h file like this.

    typedef NS_ENUM(NSInteger, PSOption) {
      PSOption1,
      PSOption2,
      PSOption3,
      PSOption4,
    };  
    

    You can then use it in your case statement and even pass it into functions as well as a type e.g.

    - (void)myMethod:(PSOption)option;
    

    A further advantage of doing this over a #define is code completion and compiler checking

    0 讨论(0)
提交回复
热议问题