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

A searchbar has to display a result where each of it must contain all of the searched words, regardless of the order in which they were written?

在 Swift 5.3 中,在我的搜索栏中,我想显示一个结果表视图,其中每个单元格都必须包含所有搜索到的词,而不管它们在搜索栏中的书写顺序。

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

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

我的表格视图在搜索之前显示这个数组:

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: 1800),
              Object(story:"your vocabulary and 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 ({[=14=].story.lowercased().range(of: searchText.lowercased()) != nil})
                
                           filteredArray += Array.filter ({[=14=].story.lowercased().range(of: searchText.lowercased()) != nil})
                           tableView.reloadData()
               }

您可以创建一组给定的搜索词,然后使用 filter 使用 allSatisfy[=14= 根据 story 检查搜索文本中的所有词]

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