I\'m trying to use a UISearchView
to query google places. In doing so, on text change calls for my UISearchBar
, I\'m making a request to google pla
A couple subtle improvements on quickthyme's excellent answer:
delay
parameter, perhaps with a default value.Debounce
an enum
instead of a class
, so you can skip having to declare a private init
.enum Debounce {
static func input(_ input: T, delay: TimeInterval = 0.3, current: @escaping @autoclosure () -> T, perform: @escaping (T) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
guard input == current() else { return }
perform(input)
}
}
}
It's also not necessary to explicitly declare the generic type at the call site — it can be inferred. For example, if you want to use Debounce
with a UISearchController
, in updateSearchResults(for:)
(required method of UISearchResultsUpdating
), you would do this:
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
Debounce.input(text, current: searchController.searchBar.text ?? "") {
// ...
}
}