Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 656
abbood Avatar asked May 03 '26 13:05

abbood


1 Answers

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;
}
like image 110
Jeff Avatar answered May 05 '26 05:05

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!