我实现了OR过滤器,
如果用户输入" NBA LA", 这个数组中的任何项目" appDel.dataFetcher?.appTitles"将以OR模式搜索。
但是,我不知道如何实施AND模式。
那就是任何选定的项目必须同时在其文本中包含NBA和LA
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)
答案 0 :(得分:1)
您可以使用NSCompoundPredicate(andPredicateWithSubpredicates:)
构建生成的 AND 谓词,如下所示:
let predicates = searchTerms.map {
return NSPredicate(format: "SELF CONTAINS[c] %@", $0)
}
let searchPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
let searchResult = ((appDel.dataFetcher?.appTitles)! as NSArray).filteredArrayUsingPredicate(searchPredicate)
let mySet = Set<String>(searchResult)
仅供参考,您可以使用componentsSeparatedByString
更轻松地拆分文字:
let searchTerms = searchController.searchBar.text!.componentsSeparatedByString(" ")