And*_*rew 3 constants objective-c switch-statement ios
有没有办法在Objective C中使用case/switch语句中的全局int常量?这里的技术(http://stackoverflow.com/questions/538996/constants-in-objective-c)让我可以在任何地方访问常量,但不允许我将它们放入switch语句中.
在.h
FOUNDATION_EXPORT const int UNIT_IDLE;
FOUNDATION_EXPORT const int UNIT_DEFEND;
Run Code Online (Sandbox Code Playgroud)
在.m
int const UNIT_IDLE = 0;
int const UNIT_DEFEND = 1;
Run Code Online (Sandbox Code Playgroud)
错误是"表达式不是整数常量表达式"
我通常在使用常量时使用带有typedef语句的枚举,我将在switch语句中使用这些常量.
例如,这将在一个共享的.h文件中,例如ProjectEnums.h:
enum my_custom_unit
{
MyCustomUnitIdle = 1,
MyCustomUnitDefend = 2
};
typedef enum my_custom_unit MyCustomUnit;
Run Code Online (Sandbox Code Playgroud)
然后,我可以在.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;
};
Run Code Online (Sandbox Code Playgroud)
这也允许编译器验证传递给方法的数据,并在编译时在switch语句中使用.
| 归档时间: |
|
| 查看次数: |
6029 次 |
| 最近记录: |