Created
June 1, 2022 15:13
-
-
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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