我如何实现AND搜索过滤器



实现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)

您可以使用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(" ")

最新更新