Is it possible to loop through enum values in Objective-C?
Join them; it only takes a minute:
|
|
Given
you can iterate the elements like:
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. |
||||
|
If you enum is defined as follows:
You can loop through it this way:
|
|||||||||||||||||||||
|
|
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... |
|||||||||
|
|
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.
To be able to loop over it, I define the following preprocessor macro.
Then I use it inside a loop, as such:
This puts the logic for iterating in one place (the macro) which increases code maintainability. |
|||
|
|
|
I like what I got from here Iteration over enum in Objective C?
that way you can keep adding enums later on and not affect your loops? |
||||
|
|
|
For non-contiguous enums you can iterate over valid values by doing:
|
|||
|
|
|
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.
|
|||
|
|