【问题标题】:How can I filter array according to another array in swift?如何快速根据另一个数组过滤数组?
【发布时间】:2020-02-25 17:02:52
【问题描述】:

我的表格视图中有搜索栏及其搜索订单 ID,此时我有另一个数组,其中包含根据订单 ID 的一些数据。我的搜索栏工作正常,过滤数组工作正常,但其他数组不工作。 (订单id和订单内容有冲突) 订单顺序发生变化。如何连接这两个阵列? 这是我的代码:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: sipCellId, for: indexPath) as! sipCell

    if isSearching {
        searched = filteredArray[indexPath.row]


    }else{
        searched = self.orderId[indexPath.row]

    }


     cell.orderIdLabel.text = searched
     cell.detailLabel.text =  self.newDatas[indexPath.row]



     return cell

}

这里是我的搜索栏功能:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if mainSearchBar.text == nil || mainSearchBar.text == "" {
        isSearching = false
        view.endEditing(true)
        tableView.reloadData()
    }else {
        isSearching = true
        filteredArray = orderId.filter({$0.range(of: mainSearchBar.text!, options: .caseInsensitive) != nil})

        tableView.reloadData()
    }
}

【问题讨论】:

  • 什么是另一个数组
  • 我在代码中看到了 3 个数组,filteredArray、orderId 和 newDatas,但我不知道您的意思是哪 2 个以及冲突是什么意思。你需要澄清你的问题。

标签: ios swift xcode searchbar


【解决方案1】:

您的问题的上下文不够清楚,您应该澄清更多,但一般来说,如果您想根据另一个数组的元素(根据您的标题问题)过滤原始数组,您可以简单地过滤原始数组并询问是否其他数组包含该元素。

originalArray = originalArray.filter{otherArray.contains($0)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2014-05-03
    • 2022-08-11
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多