5

Say I have NSArray *x = @[@1, @2, @3, @4];

Now say I want an array like @[@2, @4, @6, @8]

In good ole Swift, I can just do :

xDoubled = x.map({($0) * 2})

Can someone tell me how I can do this in Objective-C without doing -

NSMutableArray *xDoubled = [NSMutableArray new];
for (NSInteger xVal in x) {
    [xDoubled addObject:xVal * 2];
}

?

Karlo A. López
  • 2,548
  • 3
  • 29
  • 56
gran_profaci
  • 8,087
  • 15
  • 66
  • 99
  • 1
    http://www.openradar.me/radar?id=5364414152704000 (and mine's a duplicate of a much older request). There is no map method in Cocoa today. – Rob Napier Aug 14 '15 at 00:33

2 Answers2

3

NSArray doesn't have a map method. It has an enumerateObjectsUsingBlock: method (and related ones) that do something similar; they don't automatically convert an object into another and return another array, but you can do that manually easily enough. However, they're not all that much different than your example.

I wrote a library called collections that adds a map method (and other collections-oriented methods) to NSArray, NSDictionary, and NSSet, though.

mipadi
  • 398,885
  • 90
  • 523
  • 479
1

I don't necessarily recommend this, but you can do some funky stuff leveraging categories and Key-Value Coding. For example:

@interface NSNumber (DoubledValue)
- (NSNumber*) doubledValue;
@end

@implementation NSNumber (DoubledValue)
- (NSNumber*) doubledValue
{
    return @([self doubleValue] * 2);
}
@end

xDoubled = [x valueForKey:@"doubledValue"];

In general, for any operation that can be expressed as a key or key path to a property of the object, -valueForKey[Path]: acts as a primitive form of map().

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154