Iteration over enum in Objective C?

Viewed 31931

I have

enum Colour {
    white,
    pink,
    yellow,
    blue
} Colour;

and I would like to do something like this:

for (int colour in Colour){
    // Do something here.
}

Can I do this and if yes, how? Thanks for your help!

6 Answers

"Count" element in enum is nice, but it will get you "Not all switch cases were handled" in switch statement unless you handle this "count" element in it. Maybe a little better way is to use aliases for the first and for the last elements:

enum Colour {
    firstColour = 0,

    white = firstColour,
    pink,
    yellow,
    blue,

    lastColour = blue
} Colour;

for (int i = firstColour; i <= lastColour; ++i) {

}

This is a perfect use case for using a pre-processor to avoid dirtying up your compiled code


In your .h:

typedef NS_ENUM(NSUInteger, EnumValue)
{
    EnumValueOne,
    EnumValueTwo,
    EnumValueThree,
    EnumValueFour
#define EnumValueLast EnumValueFour
};

Elsewhere in app:

for (EnumValue value = 0; value <= EnumValueLast; value++) {
    //do stuff
}
Related