newBike newBike - 1 year ago 70
Swift Question

How could I implement AND search filter

I implements OR filter,

if user types "NBA LA",
Any item in this array "appDel.dataFetcher?.appTitles" will be searched with OR mode.

However, I don't know how to implement AND mode.

That is any selected item must have NBA and LA in its text at the same time


let searchTerms = searchController.searchBar.text!.characters.split{$0 == " "}.map(String.init)
for term: String in searchTerms {
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", term)
let array = ((appDel.dataFetcher?.appTitles)! as NSArray).filteredArrayUsingPredicate(searchPredicate)
searchResult += array as! [String]
let mySet = Set<String>(searchResult)

Answer Source

You can build up your resulting AND predicate using NSCompoundPredicate(andPredicateWithSubpredicates:) like below:

let predicates = {
  return NSPredicate(format: "SELF CONTAINS[c] %@", $0)

let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)

FYI, you can also split your text much more easier using componentsSeparatedByString:

let searchTerms = searchController.searchBar.text!.componentsSeparatedByString(" ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download