Objective C中的枚举迭代

我有

enum Colour { white, pink, yellow, blue } Colour; 

我想要做这样的事情:

 for (int colour in Colour){ // Do something here. } 

我可以这样做,如果是的话,怎么样? 谢谢你的帮助!

一个枚举来自C,而快速枚举是一个Objective-C 2.0的增加..他们不一起工作。

 Type existingItem; for ( existingItem in expression ) { statements } 

expression式必须符合NSFastEnumeration协议,并成为一个对象! 枚举的“元素”不是对象。

请参阅此链接了解更多信息Apple的快速枚举文档

查看这个例子来看看枚举是如何工作的:

 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]); } 

虽然这个问题已经得到解答,但是我的两分钱是:

 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); 

我想这不是那么糟糕,而且非常接近你想要的快速枚举。

在枚举中的“计数”元素是很好的,但它会得到你“不是所有的开关情况下处理” switch语句,除非你处理这个“count”元素。 也许一个更好的方法是使用别名的第一个和最后一个元素:

 enum Colour { firstColour = 0, white = firstColour, pink, yellow, blue, lastColour = blue } Colour; for (int i = firstColour; i <= lastColour; ++i) { } 

我也来到这个post回答这个问题。 戈布拉的回答非常好。 但是,我的项目数量可能会波动,并与一个存储的值相关联,所以为了“colorsCount”计数是或从来没有一个有效的值是非常安全的,我结束了实施以下,并希望增加讨论:

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]; ... } 

值得注意的是在for()迭代中使用了MYColorTypeFirst()和MYColorTypeLast()的定义,放置在枚举定义的可维护性附近。

对于我不是枚举的作者的情况,我是这样做的。 我认为这是相当安全的,因为它并不关心枚举types是如何实现的。

  UISwipeGestureRecognizerDirection allDirections[] = { UISwipeGestureRecognizerDirectionDown, UISwipeGestureRecognizerDirectionLeft, UISwipeGestureRecognizerDirectionRight, UISwipeGestureRecognizerDirectionUp }; for (int i = 0; i < sizeof(allDirections)/sizeof(allDirections[0]); ++i) { UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipe:)]; swipeGesture.direction = allDirections[i]; [self addGestureRecognizer:swipeGesture]; }