Range Over Built in Objective-C

Here we use range to sum the numbers in an array. Arrays work like this too.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
   @autoreleasepool {
      NSArray *nums = @[@2, @3, @4];
      int sum = 0;

      for (NSNumber *num in nums) {
         sum += [num intValue];
      }
      NSLog(@"sum: %d", sum);

      // `range` on arrays and slices provides both the index and value for each entry. 
      // Above we didn’t need the index, so we ignored it with the blank identifier `_`. Sometimes we actually want the indexes though.
      for (NSUInteger i = 0; i < [nums count]; i++) {
         if ([nums[i] intValue] == 3) {
             NSLog(@"index: %lu", (unsigned long)i);
         }
      }

      // `range` on map iterates over key/value pairs.
      NSDictionary *kvs = @{@"a": @"apple", @"b": @"banana"};
      for (NSString *key in kvs) {
         NSLog(@"%@: %@", key, kvs[key]);
      }

      // `range` can also iterate over just the keys of a map.
      for (NSString *key in kvs) {
         NSLog(@"key: %@", key);
      }

      // `range` on strings iterates over Unicode code points. The first value is the starting byte index of the `rune` and the second the `rune` itself.
      NSString *str = @"go";
      [str enumerateSubstringsInRange:NSMakeRange(0, [str length])
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         NSLog (@"%lu %u", (unsigned long)substringRange.location, [substring characterAtIndex:0]);
      }];
   }
   return 0;
}

To run the program, save the code in a file called rangeOverBuiltInTypes.m and use clang to compile it.

$ clang -fobjc-arc -framework Foundation -o rangeOverBuiltInTypes rangeOverBuiltInTypes.m
$ ./rangeOverBuiltInTypes
sum: 9
index: 1
a: apple
b: banana
key: a
key: b
0 103
1 111

Now that we can iterate over various built-in types, let’s learn more about Objective-C.