struct Objects {
var sectionName : String!
var sectionObjects : [CountryList]!
}
var objectArray = [Objects]()
这里objectArray
是我的tableView
数据源,其中sectionObjects
是CountryList
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()
}
}
并出现两个错误:
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/