I have this lines of code in Swift:
let graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
let average = graphPoints.reduce(0, combine: +) / graphPoints.count
It is possible to "translate" this lines of code in objective c code?
It's not very clear for me how reduce combine concept works. I read about it but still is unclear.
I took the code from this tutorial: http://www.raywenderlich.com/90693/modern-core-graphics-with-swift-part-2
Please help. Thanks.
For Objective-C, I would add the Higher-Order-Functions to this list of answers: https://github.com/fanpyi/Higher-Order-Functions
#import <Foundation/Foundation.h>
typedef id (^ReduceBlock)(id accumulator,id item);
@interface NSArray (HigherOrderFunctions)
-(id)reduce:(id)initial combine:(ReduceBlock)combine;
@end
#import "NSArray+HigherOrderFunctions.h"
@implementation NSArray (HigherOrderFunctions)
-(id)reduce:(id)initial combine:(ReduceBlock)combine{
id accumulator = initial;
for (id item in self) {
accumulator = combine(accumulator, item);
}
return accumulator;
}
@end
example:
NSArray *numbers = @[@5,@7,@3,@8];
NSNumber *sum = [numbers reduce:@0 combine:^id(id accumulator, id item) {
return @([item intValue] + [accumulator intValue]);
}];
NSNumber *multiplier = [numbers reduce:@1 combine:^id(id accumulator, id item) {
return @([item intValue] * [accumulator intValue]);
}];
NSLog(@"sum=%@,multiplier=%@",sum,multiplier);
let's say you have some NSNumber
s stored in an NSArray
you can use this KVC collection operator:
NSArray *someNumbers = @[@0, @1.1, @2, @3.4, @5, @6.7];
NSNumber *average = [someNumbers valueForKeyPath:@"@avg.self"];
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