如何在TableView中按节和行进行搜索?
从网站获取嵌套的JSON。
self.partnerBranchs = try decoder.decode([PartnerBranch].self, from: data)
型号:
struct PartnerBranch: Decodable {
let id: Int?
let address: String?
let contacts: String?
let name: String?
let logo: String?
let stocks: [Stock]
}
struct Stock: Decodable {
let id: Int?
let title: String?
let description: String?
let images: String?
}
PartnerBranch 是部分 库存是行
如何同时搜索?
现在仅适用于以下部分:
func filterContentForSearchText(_ searchText: String) {
partnerBranchsFiltered = partnerBranchs.filter({ (partnerBranch: PartnerBranch) -> Bool in
return partnerBranch.name!lowercased().contains(searchText.lowercased()
})
据我了解,我必须以某种方式将compactMat用于股票。
答案 0 :(得分:0)
我认为您需要在此处使用reduce。从我对您的问题的了解来看,如果搜索字词与您的部分标题匹配,您似乎希望显示整个部分。但是,如果没有,您仍要显示该部分以及匹配的行。因此,您可以像这样通过reduce来实现,
let filteredBranchs: [PartnerBranch] = partnerBranchs.reduce(into: []) { (result, branch) in
let partnerNameMatches = branch.name?.lowercased().contains(searchText.lowercased()) ?? false
if partnerNameMatches {
result.append(branch)
} else {
let rowMatches = branch.stocks.filter({ (stock) -> Bool in
return stock.title?.lowercased().contains(searchText.lowercased()) ?? false
})
if !rowMatches.isEmpty {
var filteredPartnerBranch = branch
filteredPartnerBranch.stocks = rowMatches
result.append(filteredPartnerBranch)
}
}
}
答案 1 :(得分:0)
最近给出了答案,但由于某些原因已被删除:
let normalizedPhrase = searchText.lowercased()
partnerBranchsFiltered = partnerBranchs.filter { (partnerBranch) in
let normalizedName = partnerBranch.name?.lowercased() ?? ""
return normalizedName.contains(normalizedPhrase) || partnerBranch.stocks!.contains { $0.title?.lowercased().contains(normalizedPhrase) ?? false }
}
它对我有用,但是现在我得到了错误线程1:致命错误:索引超出范围
return partnerBranchsFiltered[section].stocks!.count