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];
}
?
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With