Objective-C Map with index

I have a previous post on map in Objective-C and some simple use cases for it. Another variation is you might want to know the index position of the object you are mapping in the array. ¬†In order to get the index, we’ll have to use enumerateObjectsUsingBlock:

[someArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  NSLog(@"current index is %d", idx);

Now that we know how we’re going to get our index, we can continue on by creating the message signature.

-(NSArray *)arrayByMappingObjectsUsingBlockWithIndex:(id(^)(id, NSUInteger, BOOL*))blockWithIndex;

You can also create a typedef for the block.

typedef id(^MapBlockWithIndex)(id object, NSUInteger idx, BOOL *stop);
@interface NSArray (Map)
- (NSArray *)arrayByMappingObjectsUsingBlockWithIndex:(MapBlockWithIndex)blockWithIndex;

The final step is to create the the implementation which requires us to have a temporary mutable array that we append to when executing enumerateObjectsUsingBlock:

- (NSArray *)arrayByMappingObjectsUsingBlockWithIndex:(id(^)(id, NSUInteger, BOOL *))blockWithIndex
	NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
	[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
		[result addObject:blockWithIndex(obj, idx, stop)];
	return result;

That’s it! Here is the updated link to the repo with the previous version of map as well.