Skip to content

Instantly share code, notes, and snippets.

@NikolajMosbaek
Created June 1, 2022 15:13
Show Gist options
  • Save NikolajMosbaek/4255c6de45f4c78e3ba1bd5db16dcf94 to your computer and use it in GitHub Desktop.
Save NikolajMosbaek/4255c6de45f4c78e3ba1bd5db16dcf94 to your computer and use it in GitHub Desktop.
With this code you can make an object Searchable and define which parameters that should be included in a search. Then you can easily call .fullyFilter(for: someString) on the object:
protocol Searchable {
var keyPaths: [KeyPath<Self, String>] { get }
}
extension Searchable {
func matches(_ searchString: String) -> Bool {
for path in keyPaths {
let value = self[keyPath: path]
if value.localizedCaseInsensitiveContains(searchString) {
return true
}
}
return false
}
}
extension Sequence where Element: Searchable {
func fuzzyFilter(for searchString: String) -> [Element] {
filter { $0.matches(searchString) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment