【问题标题】:Filtering an array with large number of Items in Swift在 Swift 中过滤具有大量项目的数组
【发布时间】:2021-08-25 17:47:54
【问题描述】:

我正在尝试通过过滤一个包含 3000 多个项目的数组来在 tableview 中实现搜索,并且正如预期的那样,结果是一个非常慢的搜索(在按下键几秒钟后,字母出现在搜索字段中)。有关如何加快搜索速度的任何建议?

我尝试过使用filteredClips.filter { $0.text?.range(of: searchField.stringValue, options: [ .caseInsensitive, .anchored ]) != nil },但结果与下面的代码相同。

func controlTextDidChange(_ obj: Notification) {
     let searchText = searchField.stringValue.lowercased()
     let searchResults = filteredClips.filter {($0.text?.lowercased().contains(searchText))!
           || ($0.desc != nil && 
($0.desc?.lowercased().contains(searchField.stringValue.lowercased()))!)}

     filteredClips = searchResults
     clipsTableView.reloadData()
}

注意:我认为上面提到的慢文本输入是由于每次都等待controlTextDidChange 完成。是否可以在不等待controlTextDidChange 完成每个字符的情况下继续插入字符?

【问题讨论】:

  • 您的收藏是否按字典顺序排序?
  • 您可以根据用户输入的第一个字母进行过滤,然后将所有匹配项保存在一个新数组中。然后当用户输入第二个字母时,只需过滤(现在更小)数组,并将结果保存在另一个(甚至更小)数组中。这会更快。
  • @LeoDabus 不,他们不是。这是按照添加项目的顺序。
  • @Eric33187 如果用户要删除一个字母,则不会过滤相同的较小数组。
  • @unknown 如果用户删除了一个字母,你应该取前一个已经排序的数组。您必须在用户键入时跟踪数组。总而言之,您基本上需要检测用户是否添加或删除了一封信,并采取适当的行动。

标签: arrays swift search filter


【解决方案1】:

您应该使用文本字段委托并尝试按用户输入的每个字符用户进行搜索。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (searchText.text! as NSString).replacingCharacters(in: range, with: string)
        let count = text.count
        if count > 1
        {
            searchList = searchText.text!.isEmpty ? searchList : searchList.filter({(searchListTitle: searchListDataModel) -> Bool in
                // If dataItem matches the searchText, return true to include it
                return searchListTitle.title?.range(of: searchText.text!, options: .caseInsensitive) != nil
            })
            
            tableView.reloadData()
            return true
        } else {
            tableViewList = searchList
            tableView.reloadData()
            return true
        }
        
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多