本文介绍了带大小写/开关的目标C全局常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以在case / switch语句中使用Objective C中的全局int常量?这里的技术(http://stackoverflow.com/questions/538996/constants-in-objective-c)使我可以在任何地方访问常量,但不能让我将其放入switch语句中。

Is there any way to use global int constants in Objective C that work in a case/switch statement? The technique here (http://stackoverflow.com/questions/538996/constants-in-objective-c) lets me access the constants everywhere, but does not let me put them into a switch statement.

in .h

FOUNDATION_EXPORT const int UNIT_IDLE;
FOUNDATION_EXPORT const int UNIT_DEFEND;

in .m

int const UNIT_IDLE = 0;
int const UNIT_DEFEND = 1;

错误是表达式不是整数常量表达式

Error is "Expression is not an integer constant expression"

推荐答案

在使用将在switch语句中使用的常量时,我​​通常使用带有typedef语句的枚举。

I usually use enumerations with typedef statements when using constants which I will use in a switch statement.

例如,这将位于诸如ProjectEnums.h之类的共享.h文件中:

For example, this would be in a shared .h file such as ProjectEnums.h:

enum my_custom_unit
{
    MyCustomUnitIdle    = 1,
    MyCustomUnitDefend  = 2
};
typedef enum my_custom_unit MyCustomUnit;

然后我可以在.c,.m,.cpp中使用类似于以下switch语句的代码文件:

I can then use code similar to the following switch statement in my .c, .m, .cpp files:

#import "ProjectEnums.h"

- (void) useUnit:(MyCustomUnit)unit
{
    switch(unit)
    {
        case MyCustomUnitIdle:
        /* do something */
        break;

        case MyCustomUnitDefend:
        /* do something else */
        break;

        default:
        /* do some default thing for unknown unit */
        break;
    };
    return;
};

这还允许编译器验证传递给该方法并在switch语句内使用的数据。编译时间。

This also allows the compiler to verify the data being passed to the method and used within the switch statement at compile time.

这篇关于带大小写/开关的目标C全局常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:53