问题描述
在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: 1500)
]
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) } })