NSArray Equivalent of Map

后端 未结 11 1785
萌比男神i
萌比男神i 2020-11-28 05:06

Given an NSArray of NSDictionary objects (containing similar objects and keys) is it possible to write perform a map to an array of specified key?

11条回答
  •  再見小時候
    2020-11-28 05:53

    @implementation NSArray (BlockRockinBeats)
    
    - (NSArray*)mappedWithBlock:(id (^)(id obj, NSUInteger idx))block {
        NSMutableArray* result = [NSMutableArray arrayWithCapacity:self.count];
        [self enumerateObjectsUsingBlock:^(id currentObject, NSUInteger index, BOOL *stop) {
            id mappedCurrentObject = block(currentObject, index);
            if (mappedCurrentObject)
            {
                [result addObject:mappedCurrentObject];
            }
        }];
        return result;
    }
    
    @end
    


    A slight improvement upon a couple of the answers posted.

    1. Checks for nil—you can use nil to remove objects as you're mapping
    2. Method name better reflects that the method doesn't modify the array it's called on
    3. This is more a style thing but I've IMO improved the argument names of the block
    4. Dot syntax for count

提交回复
热议问题