0

In the search bar result I want to do comparison using the AnchoredSearch option first and if I don't get a value in this then I want to do comparison using CaseInsensitiveSearch option only.

I have attached my code below for searchBar.

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        self.array = self.getUniqArrayData(self.array)
        filteredTableData = array.filter({ (text) -> Bool in
            let tmp: NSString = text
            var range = tmp.rangeOfString(searchText, options: (NSStringCompareOptions.AnchoredSearch | NSStringCompareOptions.CaseInsensitiveSearch ))

            return range.location != NSNotFound
        })

        if(searchText == ""){

            searchActive = false;
        } else {
            searchActive = true;
        }
        self.xyztable.reloadData()
    }

Please let me know how can I do filter using AnchoredSearch first and if I don't find anything in it then search using CaseInsensitiveSearch option.

Any example or sample code or links for this will be helpful

Karlos
  • 1,653
  • 18
  • 36

1 Answers1

4

It's straightforward sequencing. I've cleaned up a few things; tmp is unnecessary.

// I don't think you intend to overwrite the underlying data just because
// the user did a search. Did you mean to do a local variable:
let uniqArray = self.getUniqArrayData(self.array)
let tryAnchored = uniqArray.filter { (text) -> Bool in
    var range = text.rangeOfString(searchText, options: .AnchoredSearch)
    return range.location != NSNotFound
}
if tryAnchored.count > 0 {
    self.filteredTableData = tryAnchored
}
else {
    // maybe have a local 'let' here too, and if this one also comes up
    // empty, don't reload the table data at all?
    self.filteredTableData = uniqArray.filter { (text) -> Bool in
        var range = text.rangeOfString(searchText, options: .CaseInsensitiveSearch)
        return range.location != NSNotFound
    }
}
BaseZen
  • 8,650
  • 3
  • 35
  • 47