Skip to content

Instantly share code, notes, and snippets.

@janodev
Created Dec 18, 2012
Embed
What would you like to do?
// 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