Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through enum values

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

like image 879
Frank Avatar asked Nov 02 '09 17:11

Frank


People also ask

Can you loop through an enum?

An enum can be looped through using Enum. GetNames<TEnum>() , Enum.

Can you loop through an enum C ++?

C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.


2 Answers

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.

like image 53
Barry Wark Avatar answered Oct 04 '22 05:10

Barry Wark


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 } 
like image 25
ennuikiller Avatar answered Oct 04 '22 04:10

ennuikiller