How to cancel DispatchQueue.main.asyncAfter(deadline: time) in Swift3? : <h2>Description:</h2>

<p>I'm currently using the following code to see if the user has stopped typing in the searchBar. I would like to cancel it everytime the user immediately starts typing after <code>0.5</code> seconds. </p>

<p><strong>Code:</strong></p>

<pre><code>DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your function here
}
</code></pre>

<h2>Question:</h2>

<p>How do I cancel <code>DispatchQueue.main.asyncAfter</code> if the user starts typing again in <code>Swift3</code> ?</p>

<h2>What I've tried:</h2>

<p>I previously tried implementing :</p>

<pre><code>NSObject.cancelPreviousPerformRequests(withTarget: self)
self.perform(Selector(("searchForText:")), with: searchString, afterDelay: 0.5)
</code></pre>

<p>However the delay does not seem to work properly. </p>

<p><strong>More code:</strong></p>

<pre><code>//In class SearchViewController: UITableViewController, UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
    let searchString: String = searchController.searchBar.text!

    //This is what I previously tried.. which doesn't work...
    //NSObject.cancelPreviousPerformRequests(withTarget: self)
    //self.perform(Selector(("searchForText:")), with: searchString, afterDelay: 0.5)

    //A struct with the first example code shown above.
    Utils.Dispatch.delay(secondsToDelay: 1){
        print("1 second has passed ! " + searchString)
    }
}
</code></pre>
