How can I debounce a method call?

前端 未结 13 1523
醉梦人生
醉梦人生 2020-11-30 01:18

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

13条回答
  •  渐次进展
    2020-11-30 01:51

    A couple subtle improvements on quickthyme's excellent answer:

    1. Add a delay parameter, perhaps with a default value.
    2. Make 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 ?? "") {
            // ...
        }
    
    }
    

提交回复
热议问题