我想在我的搜索栏中更好地过滤我的结果。
我的数组包含:
[["object": "Ball", "color": "Red"], ["object": "Ball", "color": "Blue"], ["object": "Square", "color": "Red"]]
当我搜索 Ball 时,所有的球都会出现,但是当我添加 Red (Ball Red) 时,它也会显示正方形,我希望它只显示包含 Ball 和 Red 这两个词的对象,而不是显示仅包含的所有对象Ball 或 Red 一词之一。这可以做到吗?
下面是我的代码。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let splitText = searchText.split(separator: " ")
filteredVehicles = posts.filter {
if let s = $0["object"] as? String, splitText.index(of: Substring(s)) != nil {
return true
}
if let s = $0["color"] as? String, splitText.index(of: Substring(s)) != nil {
return true
}
return false
}
}
最佳答案
使用它您还可以实现逆序搜索(“Blue Ball”->“Ball Blue”)。
let splitText = searchText.split(separator: " ")
let filteredObjects = objects.filter {
var include = false
for text in splitText {
if let s = $0["object"], text.contains(s) {
include = true
continue
}
if let s = $0["color"], text.contains(s) {
include = true
continue
}
return false
}
return include
}
关于ios - 过滤搜索多个词,iOS,Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47925500/