Fast Enumeration In Objective-C

You can iterate through collections (arrays, etc) with ease using a language feature known as Fast Enumeration.

This enumeration is both faster than using NSEnumerator and is also much more concise as it relates to the syntax, resulting in code that is easier on the eyes.

The basic syntax looks as follows:

for (classType variable in expression )
Fast Enumeration Forward with Array

As an example, to iterate through an array, beginning to end, it’s as simple as shown here:

NSArray *array = [NSArray arrayWithObjects: 
   @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
for (NSString *element in array) 
  NSLog(@"Beer: %@", element);
Fast Enumeration Backwards with Array

Fast Enumeration supports using NSEnumerator objects, so for example, if you want to output the same array shown above in reverse order, call the the reverseObjectEnumerator method on the array, which will return a NSEnumerator and use that within the Fast Enumeration loop:

for (NSString *element in [array reverseObjectEnumerator]) 
  NSLog(@"Beer: %@", element);

And if you are concerned about performance of the above, you can sleep well knowing that the call to [array reverseObjectEnumerator] is evaluated only the first time through the loop.

Fast Enumeration with Dictionary

Enumerating through a dictionary is equally as simple as looping through an array – access the key as an NSString object and use that value in the valueForKey method as shown here:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
    @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA", @"hoppy", nil];
for (NSString *key in dictionary) 
   NSLog(@"%@ beer example: %@", key, [dictionary valueForKey:key]);