swift - 如何查找字符串是否包含字符串的所有字符以在 Swift 中进行实时搜索?

标签 swift livesearch

我正在尝试在我正在制作的应用程序中实现搜索。我有一个正在尝试搜索的数组,我在网上找到了这段代码:

 func filterContentForSearchText(searchText: String) {
        filteredCandies = candies.filter({( candy : Candies) -> Bool in
        if         candy.name.lowercaseString.containsString(searchText.lowercaseString) == true  {
            return true
        } else {
            return false
        }
    })
    tableView.reloadData()
}

问题是我尝试在其上实现搜索的数据库中的文本全都被打乱了,因为它应该被缩短。我怎样才能做到这一点,以便搜索将检查是否所有字母都存在,而不是搜索完全正确的名称。来自数据库 (USDA) 的对象示例:CRAB、DUNGINESS、RAW 如果您有答案,请使其足够快以进行实时搜索。非实时搜索让搜索变得很糟糕(至少对我而言)!

我正在使用 Swift 2.2 和 Xcode 7

最佳答案

作为对 @appzYourLife's solution 的改进,你可以用原生的 Swift 做到这一点 Set ,因为在这种情况下不一定需要计数集。这将省去对每个名称的字符进行 map(_:) 并将它们桥接到 Objective-C 的麻烦。您现在可以只使用一组 Character s,因为它们是 Hashable .

例如:

struct Candy {
    let name: String
}

let candies = [Candy(name: "CRAB"), Candy(name: "DUNGINESS"), Candy(name: "RAW")]    
var filteredCandies = [Candy]()

func filterContentForSearchText(searchText: String) {
    let searchCharacters = Set(searchText.lowercaseString.characters)
    filteredCandies = candies.filter {Set($0.name.lowercaseString.characters).isSupersetOf(searchCharacters)}
    tableView.reloadData()
}

filterContentForSearchText("RA")
print(filteredCandies) // [Candy(name: "CRAB"), Candy(name: "RAW")]

filterContentForSearchText("ED")
print(filteredCandies) // Candy(name: "DUNGINESS")]

还取决于您是否可以将此确定为性能瓶颈(您应该先进行一些分析)——您可以通过缓存包含“糖果”名称字符的集合来进一步优化上述内容,从而避免重新创建它们在每次搜索时出现(尽管如果您更新您的 candies 数据,您必须确保它们已更新)。

来搜索的时候可以用zip(_:_:)flatMap(_:)从而筛选出对应的糖果。

let candies = [Candy(name: "CRAB"), Candy(name: "DUNGINESS"), Candy(name: "RAW")]

// cached sets of (lowercased) candy name characters
let candyNameCharacterSets = candies.map {Set($0.name.lowercaseString.characters)}

var filteredCandies = [Candy]()

func filterContentForSearchText(searchText: String) {
    let searchCharacters = Set(searchText.lowercaseString.characters)
    filteredCandies = zip(candyNameCharacterSets, candies).flatMap {$0.isSupersetOf(searchCharacters) ? $1 : nil}
    tableView.reloadData()
}

关于swift - 如何查找字符串是否包含字符串的所有字符以在 Swift 中进行实时搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937570/

相关文章:

ios - 将 RxDataSource 添加到 UICollectionView 时 Xcode 崩溃

ios - 当我的分数增加时调用随机 SKAction?

core-data - Swift - 将支持 iCloud 的持久存储添加到核心数据

javascript - 如何确保在实时 Ajax 搜索中获取最新搜索结果

PHP 示例 AJAX 实时搜索

ios - 突出显示要按下的按钮,并取消突出显示未按下的按钮SWIFT

ios - 更改出列的注释 View 的图像会导致先前使用的图像短暂出现

javascript - 具有多个单词的实时搜索过滤器,使用 AND 而不是 OR

javascript - 无法使用数据实时搜索 + jquery 多个填充 Bootstrap 选择

javascript - 使用 JQUERY 显示嵌套 JSON