Skip to content

Instantly share code, notes, and snippets.

@vhart
Last active June 9, 2018 21:41
Show Gist options
  • Save vhart/ce91b465baf053db62061efa3479b330 to your computer and use it in GitHub Desktop.
Save vhart/ce91b465baf053db62061efa3479b330 to your computer and use it in GitHub Desktop.
Filter3
struct Filter<Object> {
let keyPath: PartialKeyPath<Object>
private let matcher: (Any) -> Bool
init<Type>(keyPath: KeyPath<Object, Type>, matcher: @escaping (Type) -> Bool) {
self.keyPath = keyPath
self.matcher = { value in
let typedValue = value as! Type
return matcher(typedValue)
}
}
func matchesAgainst(_ object: Object) -> Bool {
let value = object[keyPath: keyPath]
return matcher(value)
}
static func apply<T>(_ filters: [Filter<T>], to collection: [T]) -> [T] {
return collection.filter { object in
for filter in filters {
guard filter.matchesAgainst(object) else { return false }
}
return true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment