newBike newBike - 5 months ago 14
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)


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(" ")