Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Swift's .map in Objective C? [duplicate]

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];
}

?

like image 618
gran_profaci Avatar asked Sep 28 '22 01:09

gran_profaci


2 Answers

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.

like image 100
mipadi Avatar answered Dec 01 '22 11:12

mipadi


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().

like image 45
Ken Thomases Avatar answered Dec 01 '22 10:12

Ken Thomases