【问题标题】:Filtering nested array of struct in swift 5在swift 5中过滤嵌套的结构数组
【发布时间】:2019-06-24 21:59:14
【问题描述】:
struct Objects {
        var sectionName : String!
        var sectionObjects : [CountryList]!
    }

var objectArray = [Objects]()

这里objectArray 是我的tableView 数据源,其中sectionObjectsCountryList struct 的数组。

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()
    }
}

得到两个错误:

调用 'contains' 的结果未被使用

预期返回“Bool”的闭包中缺少返回

我在这里缺少什么?任何建议将不胜感激。

提前致谢。

【问题讨论】:

  • 你的包含被隐藏在一个 for 循环中。
  • 鉴于您的init,如果不是,请不要将变量设为可选String?,因此请删除init 方法和所有? 尾随,然后您将得到结构的自动初始化

标签: arrays swift struct closures


【解决方案1】:

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 中的主要内容

【讨论】:

  • 非常感谢您的解决方案。我正在努力将它容纳在同一个数组中。让我试试不同的filterArray
  • 你需要var isSearching = true/false注册当前状态等正确配置tableView委托和数据源返回/使用相关数组
  • 好吧,我想我不需要var sectionName : String! 了我的objectArray.filter。是否可以获得唯一的var sectionObjects : [CountryList]! 列表?因为我不需要维护任何section header。生活会更轻松。再次感谢您的宝贵时间。
  • 谢谢。我看到的每个答案都只返回了内部对象。这是最好的解决方案。
猜你喜欢
  • 2022-01-25
  • 2016-10-29
  • 2017-01-28
  • 1970-01-01
  • 2022-01-22
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多