teohm.dev

I enjoy life, and make stuff for people I care about :)

Objective-C Collection Operators

Calculate average - a shorter way

When you have a collection of Transactions objects and want to calculate its average amount, instead of looping through the collection like this:

1
2
3
4
5
double sum = 0;
for (Transaction *transaction in transactions) {
    sum += [transaction.amount doubleValue];
}
NSNumber *avg = [NSNumber numberWithDouble:(sum / [transactions count])];

you can reduce the loop to 1 line of code, using Objective-C key-value coding:

1
NSNumber *avg = [transactions valueForKeyPath:@"@avg.amount"];

Currently, there is a fixed set of collection operators:

  • Simple collection operators (@avg, @count, @sum, @max, @min)
  • Object operators (@distinctUnionOfObjects, @unionOfObjects)
  • Array and set operators (@distinctUnionOfArrays, @unionOfArrays)

For details, refer to more usage examples.

Comments