Skip to content

Instantly share code, notes, and snippets.

@lexrus
Created April 24, 2017 08:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lexrus/7ba80e9f09c533165044ad61d29e75e6 to your computer and use it in GitHub Desktop.
Save lexrus/7ba80e9f09c533165044ad61d29e75e6 to your computer and use it in GitHub Desktop.
Avoid hard-coded KVC collection operators
import Foundation
enum CollectionOperator: String {
case avg
case count
case max
case min
case sum
case unionOfObjects
case distinctUnionOfObjects
case distinctUnionOfArrays
case unionOfArrays
case distinctUnionOfSets
}
precedencegroup Additive {
associativity: left
}
precedencegroup Multiplicative {
associativity: left
higherThan: Additive
}
infix operator => : Multiplicative
func => (lhs: CollectionOperator, rhs: String) -> String {
return "@" + lhs.rawValue + "." + rhs
}
let a = ["2.1", "-10", "2.1", "5", "2.5", "hello"]
let b = a as NSArray
// @avg.doubleValue
b.value(forKeyPath: .avg => #keyPath(String.doubleValue))
// @distinctUnionOfObjects.length
b.value(forKeyPath: .distinctUnionOfObjects => #keyPath(String.length))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment