To emulate a Java enumeration, we need something comparable (there may be operands == , etc.), which can have fields and are lightweight. This involves structures, and possibly pointers to structures. Here is an example of the latter:
FXLayerType.h:
typedef const struct { int persistence; } FXLayerType; extern FXLayerType * const LayerTypeExplosion; extern FXLayerType * const LayerTypeFirework; extern FXLayerType * const LayerTypeDust;
FXLayerType.m:
#import "FXLayerType.h" const FXLayerType _LayerTypeExplosion = { 3 }; const FXLayerType _LayerTypeFirework = { 6 }; const FXLayerType _LayerTypeDust = { 3 }; FXLayerType * const LayerTypeExplosion = &_LayerTypeExplosion; FXLayerType * const LayerTypeFirework = &_LayerTypeFirework; FXLayerType * const LayerTypeDust = &_LayerTypeDust;
So, FXLayerType is a struct constant, whereas, as in Obj-C objects, we always use pointers to these structures. The implementation creates 3 constant structures and 3 constant pointers to them.
Now we can write the code, for example:
FXLayerType *a, *b; a = LayerTypeDust; b = LayerTypeExplosion; NSLog(@"%d, %d\n", a == b, a->persistence == b->persistence);
Which will output "0, 1" - a and b will be different enumerations (0), but will have the same stability (1). Note that here a and b are not constant pointers, only enumerated "literals" are defined as constants.
As indicated, this has the disadvantage that you cannot switch by enumeration value. However, if necessary, just add a second field, say tag , and run it with a unique value using a real enumeration, say FXLayerStyleTag . You can also remove indirect access if you are always happy to compare tags (for example, a.tag == b.tag`). This gives you:
FXLayerType.h:
typedef enum { ExplosionTag, FireworkTag, DustTag } FXLayerTypeTag; typedef struct { FXLayerTypeTag tag; int persistence; } FXLayerType; extern const FXLayerType LayerTypeExplosion; extern const FXLayerType LayerTypeFirework; extern const FXLayerType LayerTypeDust;
FXLayerType.m:
#import "FXLayerType.h" const FXLayerType LayerTypeExplosion = { ExplosionTag, 3 }; const FXLayerType LayerTypeFirework = { FireworkTag, 6 }; const FXLayerType LayerTypeDust = { DustTag, 3 };
Using:
FXLayerType a, b; a = LayerTypeDust; b = LayerTypeExplosion; NSLog(@"%d, %d\n", a.tag == b.tag, a.persistence == b.persistence);
The difference between the two projects is the first passes around the pointers, and the second structures, which may be larger. You can combine them to get switch capable pointer-based enumerations - this will remain as an exercise!
Both of these projects also have the advantage (dis) that the number of "literals" of an enumeration can be expanded at any time.