typestar

Fast enumeration in Objective-C

for-in walks arrays in order and dictionaries by key.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray<NSString *> *queue =
            @[ @"clean sleeve", @"grade vinyl", @"price", @"shelve" ];
        // for-in walks any collection in order.
        NSInteger step = 1;
        for (NSString *task in queue) {
            NSLog(@"%ld. %@", (long)step, task);
            step += 1;
        }
        // Dictionaries enumerate their keys.
        NSDictionary *graded = @{ @"VG+" : @12, @"NM" : @5 };
        for (NSString *grade in graded) {
            NSLog(@"%@: %@ records", grade, graded[grade]);
        }
    }
    return 0;
}

How it works

  1. for (NSString *task in queue) needs no index bookkeeping.
  2. A counter travels alongside when position matters.
  3. Enumerating a dictionary yields its keys; subscript for values.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
491
Tokens
121
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 112 seconds.

Type this snippet

Step 1 of 3 in Enumeration, step 13 of 27 in Language basics.

← Previous Next →