有没有办法在 Objective C 中使用在 case/switch 语句中工作的全局 int 常量?这里的技术(http://stackoverflow.com/questions/538996/constants-in-objective-c)让我可以访问任何地方的常量,但不允许我将它们放入 switch 语句中。
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;
错误是“表达式不是整数常量表达式”
当使用将在 switch 语句中使用的常量时,我通常将枚举与 typedef 语句一起使用。
例如,这将位于共享 .h 文件中,例如 ProjectEnums.h:
enum my_custom_unit
{
MyCustomUnitIdle = 1,
MyCustomUnitDefend = 2
};
typedef enum my_custom_unit MyCustomUnit;
然后,我可以在 .c、.m、.cpp 文件中使用类似于以下 switch 语句的代码:
#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 语句中使用的数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)