What is Fast Enumeration in iOS programming? (using Xcode 8.2.1 / iOS 10).

What is Fast Enumeration in iOS programming? (using Xcode 8.2.1 / iOS 10).

Question: What is Fast Enumeration in iOS programming?

Answer: This is the best way to traverse a collection. (like an NSArray or NSSet)

Actually, a collection can be an NSArray, NSMutableArray, NSSet, NSMutableSet, NSDictionary, NSMutableDictionary.

Let’s look at a traditional way of traversing an NSArray. First I define the array and then we just look through each item shown below:

NSArray *myArray=[NSArray arrayWithObjects:@"Hit",@"me",@"with",@"your",@"best",@"shot",nil];

        // Using a standard FOR-LOOP
        for (int i=0; i<[myArray count]; i++) {
            NSLog(@"item %d: %@", i, myArray[i]);
            }

The output is:
item 0: Hit
item 1: me
item 2: with
item 3: your
item 4: best
item 5: shot

 Now, if we use fast enumeration then the FOR-LOOP becomes:
        
          for (NSString *myStr in myArray)
            {
              NSLog(@"Value =%@",myStr);
             }


Value =Hit
Value =me
Value =with
Value =your
Value =best
Value =shot!

Moving on lets look at using fast enumeration on an NSSet. 

        NSSet *mySet = [NSSet setWithArray:@[@"Hit",@"me",@"with",@"your",@"best",@"shot"]];

        for (NSString *myStr in mySet)
        {
            NSLog(@"Value =%@",myStr);
        }

Value =shot
Value =me
Value =your
Value =Hit
Value =with
Value =best

Well….this is interesting!

      Not in the right order?!

            When do we use NSSet instead of NSArray?…..

   Let’s talk about this in the next post!!!

Leave a Reply

Your email address will not be published. Required fields are marked *