开发者

What's the Objective-C equivalent of JS's `map()` function? [duplicate]

This question already has answers here: NSArray Equivalent of Map (11 answers) Closed 7 years ago.

What's the Objective-C equivalent of JS's map() function? Would I just use NSFas开发者_开发知识库tEnumeration and apply the function myself?


You can use NSArray's enumerateObjectsUsingBlock: if you're on OS X 10.6 or iOS 4.:

NSMutableArray *mapped = [NSMutableArray arrayWithCapacity:[array count]];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    id mapObj = DoSomethingToObject(obj);
    [mapped addObject:mapObj];
}];

(Shameless but relevant plug: I have a library for OS X and iOS that adds map and other similar functionality to NSArray and NSSet.)


It depends. If you have, say, an array of objects, and these objects have a URL property (for example), then you can do:

NSArray * urls = [myArray valueForKey:@"URL"];

Likewise, if you can trigger the behavior of the objects in question via a single message that takes 0 or 1 parameters, you can do:

[myArray makeObjectsPerformSelector:@selector(doFoo)];
//or:
[myArray makeObjectsPerformSelector:@selector(doFooWithBar:) withObject:aBar];

For anything beyond that, you'll have to iterate over the objects yourself. You can use a for() loop, a for(in) loop, or something like -enumerateObjectsUsingBlock:, etc.


You do it yourself. There is no single method equivalent to what you want.

Edit: For those downvoting, this was the correct answer at the time (three years ago) and still is for Objective-C, but Swift does have a map() function.


Check BlocksKit, it provides map, reduce and filer for NSArray.

  • (NSArray *)map:(BKTransformBlock)block;
  • (id)reduce:(id)initial withBlock:(BKAccumulationBlock)block;
  • (NSArray *)select:(BKValidationBlock)block;


Category function for NSArray an alternative

- (NSArray *)map:(id(^)(id, BOOL *))block {
    NSMutableArray * array = [NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id newObject = block(obj,stop);
        if (newObject == nil) {
            newObject = [NSNull null];
        }
        [array addObject:newObject];
    }];
    return array.copy;
}

Category function for NSMutableArray an alternative

- (NSMutableArray *)map:(id(^)(id))block {
    NSEnumerator * enumerator = ((NSArray *)self.copy).objectEnumerator;
    id obj; NSUInteger idx = 0;
    while ((obj = enumerator.nextObject)) {
        self[idx] = block(obj) ?: [NSNull null];
        idx++;
    }
    return self;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜