Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is possible to use array reduce concept from swift in objective c?

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.

like image 742
Adela Toderici Avatar asked Dec 16 '15 14:12

Adela Toderici


2 Answers

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);
like image 175
范陆离 Avatar answered Oct 25 '22 21:10

范陆离


let's say you have some NSNumbers 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"];
like image 24
André Slotta Avatar answered Oct 25 '22 21:10

André Slotta