Search code examples
iosswiftuisearchcontroller

How do I filter data to startswith instead of contains


I have a UITableView that has a Search Controller for filtering the data using the code below

func updateSearchResults(for searchController: UISearchController) {
     let searchString = searchController.searchBar.text
     filteredArray = data.filter({ (country) -> Bool in let countryText: NSString = country as NSString         
     return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound })
     suggestionview.reloadData()
}

How do I make it so that the search filters the table by looking at the start of the string instead of matching anywhere.

For example currently if I type Lon into the search input I get a list of anything that contains Lon (still a huge list before getting to London).


Solution

  • Why do you use NSString? Prefer String in Swift 3+:

    filteredArray = data.filter({ (country) -> Bool in 
        let countryText: NSString = country as NSString         
        return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound })
        
    

    =>

    filteredArray = data.filter({ country -> Bool in 
        return country.range(of: searchString!, options: .caseInsensitive) != nil })
    

    You used the .caseInsenstive option, but there is also the .anchored one that migh interest you:

    Search is limited to start (or end, if NSBackwardsSearch) of source string.

    filteredArray = data.filter({ country -> Bool in 
        return country.range(of: searchString!, options: [.caseInsensitive, .anchored]) != nil })