Enums in Objective-C?
This is a syntax-based question. I'm having a bit of trouble getting enums working in Objective-C. I'm also not sure where the best place to declare them is, but within @implementation seems like it would be fine.
That's what I've been trying. The enum declaration works fine, but neither of the two assignments in doStuff are legal. Can someone just write out the proper way of doing this? Thanks.
Code:
@implementation
typedef enum animalTypes
{
DOG,
CAT,
MONKEY,
MONGOOSE
} Animals;
- (void) doStuff
{
int x = Animals.DOG;
int y = (int) Animals.DOG;
}
@endThat's what I've been trying. The enum declaration works fine, but neither of the two assignments in doStuff are legal. Can someone just write out the proper way of doing this? Thanks.
enum in C (and thereby Objective-C) is simply syntactic sugar for #define, plus a little bit of type safety. The way you're written that code, "enum animalTypes" and "Animals" are both integer types that will require all values thereof to be handled in any switch statement on variables of that type. DOG, CAT, MONKEY, and MONGOOSE are all constants that can be used directly without any prefix.
You can actually put your enums just about anywhere you want. In your example, you could put the enum outside of the implementation or inside it, but I would keep it in the .m file since it's just a part of the implementation details. My personal style would be to list it before the @implementation keyword.
If you were going to use an enum to define some constants to use a parameters to a method you should put it in the header file instead so clients can just import the header. In that case I would highly recommend keeping the enum outside of the @interface declaration. I'm not certain that it would matter syntactically, but it makes the most sense semantically.
If you were going to use an enum to define some constants to use a parameters to a method you should put it in the header file instead so clients can just import the header. In that case I would highly recommend keeping the enum outside of the @interface declaration. I'm not certain that it would matter syntactically, but it makes the most sense semantically.
So, the gist is that the OP should just do the following, correct?
Code:
@implementation
typedef enum animalTypes
{
DOG,
CAT,
MONKEY,
MONGOOSE
} Animals;
- (void) doStuff
{
Animals x = DOG;
int y = (int)DOG;
}
@end
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| How do you create enums for state charts in ObjC? | riruilo | 7 | 5,783 |
Mar 27, 2010 11:50 PM Last Post: AnotherJake |
|

