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!
|
I have
and I would like to do something like this:
Can I do this and if yes, how? Thanks for your help! |
|||||
|
|
an enum comes from C while fast enumeration was an addition of Objective-C 2.0.. they don't work together.
expression must conform to the NSFastEnumeration Protocol and be an Object! "elements" of an enum are not objects. see this link for more information Apple's Fast Enumeration Documents check this example to see how fast enumeration works:
|
|||||||||||||
|
|
Although the question is already answered, here are my two cents:
I guess it's not that bad and is pretty close to the fast enumeration you want. |
|||||||||||||||||||||
|
|
"Count" element in enum is nice, but it will get you "Not all switch cases were handled" in
|
|||
|
|
|
I came to this post to answer this question as well. Gobra's answer is great. But my number of items may fluctuate, and correlate to a stored value, so to be extra safe that the "colorsCount" count is or was never a valid value, I ended up implementing the following and wanted to add to the discussion: MYColor.h
ViewController.m
The notable addition being the definition of MYColorTypeFirst() and MYColorTypeLast(), which is used in the for() iteration, placed near the enum definition for maintainability. |
|||
|
|
|
For cases where I'm not the author of the enum, I do it like this. I think this is pretty future safe, as it doesn't cares about how the enum types are actually implemented.
|
|||