Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration over enum in Objective C?

Tags:

objective-c

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!

like image 356
Matt N. Avatar asked Aug 02 '11 09:08

Matt N.


People also ask

Can you iterate over an enum in C?

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.

How do you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

How big is an enum in C?

The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.

What is an enum in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

Although the question is already answered, here are my two cents:

enum Colour {     white = 0,     pink,     yellow,     blue,      colorsCount // since we count from 0, this number will be blue+1 and will be actual 'colors count' } Colour;  for (int i = 0; i < colorsCount; ++i)   someFunc((Colour)i); 

I guess it's not that bad and is pretty close to the fast enumeration you want.

like image 189
Gobra Avatar answered Sep 27 '22 20:09

Gobra