Skip to content

Instantly share code, notes, and snippets.

@janodev
Created December 18, 2012 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/4324665 to your computer and use it in GitHub Desktop.
Save janodev/4324665 to your computer and use it in GitHub Desktop.
// Maybe a functional category on NSArray will help.
@interface NSArray(Extension)
-(NSArray*) map:(id(^)(id object))block;
@end
@implementation NSArray(Extension)
-(NSArray*) map:(id(^)(id object))block {
NSParameterAssert(block != NULL);
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:[self count]];
for (id object in self) {
id result = block(object);
[results addObject:result];
}
return results;
}
@end
@interface Driver : NSObject
@property (strong, nonatomic) NSString *name;
@end
@implementation Driver
-(id)initWithName:(NSString*)name {
self = [super init];
if (self){
_name = name;
}
return self;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSArray *input = @[ [[Driver alloc]initWithName:@"a"], [[Driver alloc]initWithName:@"b"] ];
NSArray *drivers = [input map:^(id object){
return [object name];
}];
NSLog(@"%@",drivers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment