views:

353

answers:

3

Is it possible to loop through enum values in Objective-C?

+1  A: 

If you enum is defined as follows:

enum Direction {  East,  West,  North,  South};

You can loop through it this way:

for ( int direction = East; direction <= South; ++direction)
{
   /* Do something with Direction
}
ennuikiller
The for-loop body won't run with `direction == South`. You are missing one iteration.
notnoop
@notnoop thanks, corrected
ennuikiller
I've never done this, so I have some questions. Shouldn't it be Direction.East and Direction.South? Also shouldn't the condition be direction <= Direction.South? Again I've never done this, I'm not trying to correct you, just would like to learn.
Jorge Israel Peña
Is there a better way to do this? Just curious, but it seems like depending on the declaration order of the enum values is fragile at best.
Ed Swangren
@blaenk: i think you're confusing structs with enums.
pxl
The test statement in your for loop is incorrect.
Barry Wark
@Ed: Yes this is fragile, and no there's not a better way. It's not advisable to do this at all.
Chuck
One could be more explicit as in enum Direction { East =1, West=2, North=3, South=4}; or even enum Direction { East =313, West, North, South}; but it all comes down to the same thing, except that numbering each element leaves more room for programmer error. In the end it seems to me to be as fragile or non-fragile as any const declaration.
Elise van Looij
+4  A: 

Given

enum Foo {Bar=0,Baz,...,Last};

you can iterate the elements like:

for(int i=Bar; i<=Last; i++) {
  ...
}

Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and visa versa. In addition, this depends on the declaration order of the enum values: fragile to say the least. In addition, please see Chuck's comment; if the enum items are non-contiguous (e.g. because you specified explicit, non-sequential values for some items), this won't work at all. Yikes.

Barry Wark
It also requires that all the items in the enum be contiguous. But it's the best you'll get.
Chuck
it doesn't recognize Foo in the for looo for me.
Frank
actually, it should be int i=Bar ..... Foo is the type name.
Brian Postow
Oops... sorry about the for loop declaration typo. Fixed now.
Barry Wark
+2  A: 

It's a bit of a kludge (as is the entire concept so... eh...) but if you're going to do this multiple times, and you want to be able to deal with the possibility of non-contiguous enums, you can create a (global constant) array, and have (to use ennukiller's example) Directions directions[4] = {East, West, North, South}; and then in your loop you can talk about directions[i] rather than iterating directly over the directions themselves...

As I said, it's ugly, but it's slightly less fragile I think...

Brian Postow