The aim of this project is to tackle the disadvantages of KVC Collection Operators
The obvious advatange is clarity in consicion.
But I also want the following:
- explicit choice of operator with compile-time errors for invalid use
- explicit typing of the objects expected in the collection
- compile-time errors if I use a key path that doesn't belong to the type of object in the collection
- code-completion on key path
All macros intended for public use have the format:
MacroName(collection, typeOfObjectsInCollection, keyPath)
- collection - instance of
NSArray *,NSSet *, etc. e.g.self.transactions - typeOfObjectsInCollection - the type of objects in the collection, e.g.
Transaction *- I chose to require the full type including asterisk in order to be explicit - keyPath - dot-separated selector names, e.g.
payee.name
... with the exception of the "Added Convenience" macros for collections of NSNumber *s, see below.
I can create an array of all the names of payees for transactions, as follows:
NSArray *payeeNames = DZLUnionOfObjects(self.transactions, Transaction *, payee.name);- DZLAverage - equivalent to
@avg(but returns double) - DZLCount - equivalent to
@count(but returns double) - DZLSum - equivalent to
@sum(but returns double) - DZLMinimum - equivalent to
@minwith added compile-time validation that objects in the collection respond to-compare - DZLMaximum - equivalent to
@maxwith added compile-time validation that objects in the collection respond to-compare
- DZLAverageNumber - same as DZLAverage but checks that the key path leads to an instance of
NSNumber * - DZLSumNumber - same as DZLSum but checks that the key path leads to an instance of
NSNumber * - DZLAverageDouble - same as DZLAverage but checks that the key path leads to a
doubleor compatible scalar type - DZLSumDouble - same as DZLSum but checks that the key path leads to a
doubleor compatible scalar type
- DZLAverageOfNumbers - only takes one parameter -- a collection of
NSNumber *objects -- and returns the average as a double - DZLSumOfNumbers - only takes one parameter -- a collection of
NSNumber *objects -- and returns the sum as a double
- DZLDistinctUnionOfObjects - equivalent to
@distinctUnionOfObjects - DZLUnionOfObjects - equivalent to
@unionOfObjects
- DZLDistinctUnionOfArrays - equivalent to
@distinctUnionOfArrays - DZLUnionOfArrays - equivalent to
@unionOfArrays - DZLDistinctUnionOfSets - equivalent to
@distinctUnionOfSets
You can get the average of a collection of numbers using the macros above as follows:
double average = DZLAverage(numbers, NSNumber *, self);
I've added the convenience methods for this and for sum, which can be used as follows:
double average = DZLAverageOfNumbers(numbers);
double sum = DZLSumOfNumbers(numbers);
Use CocoaPods, or simply add DZLCollectionOperators.h file to your project.
It's as simple as that, it's just a header file with macros!
If you like this, you can follow me on twitter for more of the same!