Skip to content

Instantly share code, notes, and snippets.

@Dev1an
Last active June 8, 2017 15:32
Show Gist options
  • Save Dev1an/7eeaba910f91974904da6f0431b7fb54 to your computer and use it in GitHub Desktop.
Save Dev1an/7eeaba910f91974904da6f0431b7fb54 to your computer and use it in GitHub Desktop.
Generic predicates (in Swift 4)
extension Sequence {
func find<Property, Argument>(where predicate: (propertyPath: KeyPath<Self.Element, Property>, comparator: (Property, Argument)->Bool, argument: Argument)) -> [Self.Element] {
return filter { predicate.comparator($0[keyPath: predicate.propertyPath], predicate.argument) }
}
// A more specialised version:
func find(where characteristic: KeyPath<Self.Element, Bool>) -> [Self.Element] {
return filter { $0[keyPath: characteristic] }
}
}
// Usage
struct Car {
let model: String
let gears: UInt8
}
var cars = [Car]()
cars.find(where: (\.model, ==, "A9"))
cars.find(where: \.model.isEmpty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment