Equivalent to Swift. Map in Objective-C?

Let's say I have NSArray *x = @[@1, @2, @3, @4];

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

In a 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 execution -

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

?

+5
source share
2 answers

NSArray does not have a map method. It has an enumerateObjectsUsingBlock: method (and related ones) that do something similar; they do not automatically convert the object to another and return a different array, but you can do it manually quite easily. However, they are not so different from your example.

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

+3
source

I don't necessarily recommend this, but you can do some fun things using categories and keyword coding. For instance:

 @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 an object property, -valueForKey[Path]: acts as a primitive form of map() .

+1
source

All Articles