How to skip objects while iterating in a ruby like Map method for obj-c

cocoa, ios, iphone, objective-c, objective-c-blocks

Solution

If the implementation is similar to what you showed above, it would make sense to just apply the block result to an intermediate value and then check it before adding it to the result array. Something like this:

- (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id blockResult = block( obj, idx );
        if( result != nil ){
          [result addObject:blockResult];
        }
    }];
    return result;
}

Problem

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.

Original source

Related problems