Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
    
Retagged: this is (AFAIK) a pure C question. You'll get more response with the more general tagging. – Brian Postow Nov 2 '09 at 19:45
11  
It also answers the question for people searching for it in Obj-C. Added that tag back. – pbh101 Nov 2 '09 at 19:47

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.

share|improve this answer
7  
It also requires that all the items in the enum be contiguous. But it's the best you'll get. – Chuck Nov 2 '09 at 19:23
    
it doesn't recognize Foo in the for looo for me. – Frank Nov 2 '09 at 19:24
5  
It's a pure nitpick, but it's spelled vice versa. – new123456 Sep 28 '11 at 16:02
    
Then edit it yourself, @new123456. – Miles Rout Aug 31 '13 at 6:45
    
@MilesRout There's actually a minimum character change of 6 characters. Since it's a 2 character fix, I can't fix it. – new123456 Sep 1 '13 at 16:13

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
}
share|improve this answer
    
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 Nov 2 '09 at 18:28
3  
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 S. Nov 2 '09 at 18:34
    
@blaenk: i think you're confusing structs with enums. – pxl Nov 2 '09 at 18:37
    
The test statement in your for loop is incorrect. – Barry Wark Nov 2 '09 at 19:13
3  
@Ed: Yes this is fragile, and no there's not a better way. It's not advisable to do this at all. – Chuck Nov 2 '09 at 19:23

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...

share|improve this answer
    
Looks good to me. Is there a way that we can add some kind of macro that will automatically generate C-arrays for us for each enum type we declare? – ArtOfWarfare Nov 11 '12 at 16:40
    
@ArtOfWarfare I use this all the time: #define ENUM(type, ...) enum _##type { __VA_ARGS__ }; enum _##type type##s[] = { __VA_ARGS__ }, though that will only work for contiguous ones. I don't use non-contiguous enums, because that to me signals bad design. Also I have typedef struct _list List;, typedef enum _direction Direction everywhere in my C code that uses this macro, which is why I'm prefixing the _ to the type. ENUM(direction, NORTH, EAST, SOUTH, WEST); gives enum _direction { NORTH, EAST, SOUTH, WEST }; enum _direction directions = { NORTH, EAST, SOUTH, WEST }; I like it. – Miles Rout Aug 31 '13 at 7:29

In search of this, I just concocted the following solution which fulfilled my own requirements. I thought I'd post it here for people searching something similar.

Say I have an enum.

typedef NS_ENUM (NSInteger, ISDirection) {
  ISDirectionUp,
  ISDirectionDown,
  ISDirectionLeft,
  ISDirectionRight
};

To be able to loop over it, I define the following preprocessor macro.

#define ISDirectionAllAsDir ISDirection dir = ISDirectionUp; dir <= ISDirectionRight; dir++

Then I use it inside a loop, as such:

for(ISDirectionAllAsDir) {
  NSLog(@"Direction %d", dir);
}

This puts the logic for iterating in one place (the macro) which increases code maintainability.

share|improve this answer

I like what I got from here Iteration over enum in Objective C?

typedef enum { ENUM1=0,  ENUM2, ENUM3, ENUM4 , TOTAL  } ;


for ( int i=ENUM1 ; i<TOTAL; i++)
{}

that way you can keep adding enums later on and not affect your loops?

share|improve this answer

For non-contiguous enums you can iterate over valid values by doing:

enum {
    value_one   = 0,
    value_two   = 1,
    value_three = 3,
    value_max
}
for ( i = value_one; i < value_max; i++ )
{ 
    switch(i)
    {
        case value_one:
        case value_two:
        case value_three:
        case value_four:
        {
            /* ... Do something with valid enum value ... */
        }
        break;
        default:
            /* Found an invalid enum entry; ignore it */
        break;
    }
}
share|improve this answer

The length (count of items) of any enumeration can be ascertained by getting the array of names in the enumeration and utilizing the array's length. Use the GetNames method of Enum. Enum.GetNames(enumType).Length.

{
enum Pig { Snort, Sty, Oink, Curly };
const int Pig_Count = Enum.GetNames(typeof(Pig)).Length;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.