ios - 过滤搜索多个词,iOS,Swift

标签 ios swift search filter

我想在我的搜索栏中更好地过滤我的结果。

我的数组包含:

[["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/

相关文章:

ios - Cocoapods 将 pod 与不同的部署目标混合在一起

ios - PickerView 不显示任何值

Swift 4 协议(protocol)组合一致性

swift - 搜索超过 3 个值

search - 如何忽略 solr 查询中的空格

ios - 有没有办法以编程方式发送消息,而无需用户点击屏幕确认发送消息,而只是使用语音命令?

iphone - 你将如何实现 [UIViewController presentModalViewController]?

python - 行系列中不完全匹配的搜索算法

ios - 哪一行代码决定 iOS 项目使用 Storyboard或 Nib 或两者都不使用?

swift - 从核心数据中获取子总和