Iteration over enum in Objective C?
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
typedef NS_ENUM( NSInteger, MYColorType )
{
MYColorType0 = 0,
MYColorType1,
MYColorType2,
MYColorType3
};
static inline MYColorType MYColorTypeFirst() { return MYColorType0; }
static inline MYColorType MYColorTypeLast() { return MYColorType3; }
ViewController.m
for ( int i = MYColorTypeFirst(); i <= MYColorTypeLast(); i++ )
{
MYColor * color = [[MYColor alloc] initWithType:i];
...
}
The notable addition being the definition of MYColorTypeFirst() and MYColorTypeLast(), which is used in the for() iteration, placed near the enum definition for maintainability.
an enum comes from C while fast enumeration was an addition of Objective-C 2.0.. they don't work together.
Type existingItem;
for ( existingItem in expression ) { statements }
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:
NSArray *array = [NSArray arrayWithObjects:
@"One", @"Two", @"Three", @"Four", nil];
for (NSString *element in array) {
NSLog(@"element: %@", element);
}
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];
NSString *key;
for (key in dictionary) {
NSLog(@"English: %@, Latin: %@", key, [dictionary objectForKey:key]);
}
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.
"Count" element in enum is nice, but it will get you "Not all switch cases were handled" in switch
statement unless you handle this "count" element in it. Maybe a little better way is to use aliases for the first and for the last elements:
enum Colour {
firstColour = 0,
white = firstColour,
pink,
yellow,
blue,
lastColour = blue
} Colour;
for (int i = firstColour; i <= lastColour; ++i) {
}