Is it possible to loop through enum values in Objective-C?
An enum can be looped through using Enum. GetNames<TEnum>() , Enum.
C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.
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 vice 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:
enum Direction { East, West, North, South};
You can loop through it this way:
for ( int direction = East; direction <= South; ++direction) { /* Do something with Direction }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With