arrays - 在 swift 5 中过滤结构的嵌套数组

标签 arrays swift struct closures

struct Objects {
        var sectionName : String!
        var sectionObjects : [CountryList]!
    }

var objectArray = [Objects]()

这里objectArray是我的tableView数据源,其中sectionObjectsCountryListstruct<的数组.

struct CountryList: Codable {
    let country_id: String?
    let country_name: String?
    let country_code:  String?
    let country_flag_url: String?

    init(countryID: String, countryName: String, countryCode:  String, countryFlagURL: String) {
        self.country_id = countryID
        self.country_name = countryName
        self.country_code = countryCode
        self.country_flag_url = countryFlagURL
    }
}

我想根据 country_name 过滤我的 objectArray

这就是我在UISearchResultsUpdating中所做的。

extension CountryListViewController: UISearchResultsUpdating {
    public func updateSearchResults(for searchController: UISearchController) {
        guard let searchText = searchController.searchBar.text else {return}
        if searchText == "" {
            objectArray += objectArray
        } else {
            objectArray += objectArray

            objectArray = objectArray.filter {
                let countryListArray = $0.sectionObjects!
                for countryList in countryListArray {
                    print("cName \(String(describing: countryList.country_name))")
                    countryList.country_name!.contains(searchText)
                }
            }
        }
        self.countryListTableView.reloadData()
    }
}

并出现两个错误:

Result of call to 'contains' is unused

Missing return in a closure expected to return 'Bool'

我在这里缺少什么?任何建议将受到高度赞赏。

提前致谢。

最佳答案

filter 期望其中有一个 bool 返回,因此您需要

var objectArray = [Objects]()
var filtered = [Objects]()

filtered = objectArray.filter {
  let countryListArray = $0.sectionObjects
  for countryList in countryListArray {
    print("cName \(String(describing: countryList.country_name))")
       if countryList.country_name!.contains(searchText) {
             return true 
        } 
   }
   return false
}

或者更好

filtered = objectArray.filter { $0.sectionObjects.filter { $0.country_name!.contains(searchText) }.count != 0 }

提示:使用另一个数组filtered来保存过滤后的数据,以免覆盖objectArray中的主要内容

关于arrays - 在 swift 5 中过滤结构的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744437/

相关文章:

c# - 我应该使用结构吗?

c++ - 如何在cgo中从打包的struct处理char *?

python - 矩阵数组的逐元素有效乘法

python - 如何创建具有相同和不同长度的其他 numpy 数组的 numpy _object_ 数组?

ios - 如何从 TableView Controller 转到详细 Controller 并返回

c - 内存中的结构赋值和持久化(C语言)

C# 相当于 Delphi High() 和 Low() 函数,用于保持性能的数组?

arrays - 更新与辅助数组匹配的大型数组中的特定值(如 vlookup)

ios - 为什么图片动画在图像方向不同时效果不同

ios - UIPageViewController 在 SwiftUI 中滑动 1 次后停止工作