搜索栏必须显示一个结果,其中每个搜索结果都必须包含所有搜索到的单词,而不管它们的书写顺序如何?

问题描述

在Swift 5.3中,我想在搜索栏中显示一个结果表视图,其中每个单元格必须包含所有搜索到的单词,无论它们在搜索栏中的写入顺序如何。

示例: 我有一个对象结构:

struct Object {
  var story : String
  var age: Int
  ...
}

我的tableview在搜索之前显示此数组:

Array  : [Object] =  [
              Object(story:"English texts for beginners to practice",age: 1200),Object(story:"reading and comprehension online",age: 1600),Object(story:"and for free. Practicing your comprehension",age: 1800),Object(story:"of written English will both improve",age: 1100),Object(story:"your vocabulary and comprehension",age: 1500),Object(story:"of grammar and word order." age: 1400)
             ]

当我在搜索栏中点击“理解您”时,它将检索此过滤后的数组:

filteredArray = [
              Object(story:"and for free. Practicing your comprehension",age: 1500)
              ]

当然我有UISearchBar的功能

func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
       if searchText.isEmpty {
               filteredArray = Array // To see all the Array

self.tableView.reloadData()
}

这是我尝试过的,但不是我所需要的

if let searchBarText = searchBar.text{
                let searchText = searchBarText.lowercased()
                           filteredArray = Array.filter ({$0.story.lowercased().range(of: searchText.lowercased()) != nil})
                
                           filteredArray += Array.filter ({$0.story.lowercased().range(of: searchText.lowercased()) != nil})
                           tableView.reloadData()
               }

解决方法

您可以创建一组给定的搜索词,然后使用filter,其中使用story将搜索文本中的所有单词与allSatisfy进行比较

let words = Set(searchText.split(separator: " ").map(String.init))
let filtered = array.filter { object in words.allSatisfy { word in object.story.localizedCaseInsensitiveContains(word) } })