Using the answer here this method achieves something similar to ruby's map in obj-c:
- (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block {
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[result addObject:block(obj, idx)];
}];
return result;
}
my question is how can i skip an object if something wrong happens while applying the block? Typically to skip something in an enumerator one just use the return
command, however that's not an option in the method above, since the block is expected to return something.
In this example I use return
to skip but get an error:
NSArray *mappedArray = [objArray mapObjectsUsingBlock:^(id obj, NSUInteger i) {
// i don't want this obj to be included in final array
// so I try to skip it
return; // ERROR:incompatible block pointer types sending
// 'void(^)(__strong id, NSUInteger)' to parameter of type
// 'id(^)(__strong id, NSUInteger)'
// else do some processing
return soupedUpObj;
}];
My current way of working around it is simply returning a null object, then removing them out from the final array. But I'm sure there must be a better way than that.