【发布时间】:2020-04-06 14:34:59
【问题描述】:
我有模特
class Consumer360PurchaseHistoryDetails: Codable {
var freqofPurchase : String?
var freqofVisit : String?
var customerPurchaseHistory : [CustomerPurchaseHistory]?
init() {
}
}
class CustomerPurchaseHistory : Codable {
var dateOfPurchase : String?
var products : [PurchaseProducts]?
init() {
}
}
class PurchaseProducts : Codable {
var productID : String?
var productFilterType : String?
init() {
}
}
我想在 PurchaseProducts 中按 productFilterType 过滤这个模型
我尝试了以下方式
var dataModel: Consumer360PurchaseHistoryDetails?
var tempDataModel:Consumer360PurchaseHistoryDetails = Consumer360PurchaseHistoryDetails()
for purchaseHistory in self.dataModel?.customerPurchaseHistory ?? [] {
for product in purchaseHistory.products ?? [] {
if product.productFilterType?.lowercased() == StringConstants.purchase {
tempDataModel.freqofVisit = "three"
tempDataModel.freqofPurchase = "five"
tempDataModel.customerPurchaseHistory?.append(purchaseHistory)
}
}
}
self.purchaseHistoryTableView.dataModel = self.tempDataModel
但是 purchaseHistory 并没有附加到 customerPurchaseHistory 中,附加后始终为 nil。但是 freqofVisit 和 freqofPurchase 正在更新。我要使用索引来追加吗?
【问题讨论】:
-
这里你需要很清楚。您想准确保留哪些元素?您是要保留整个购买历史,只要它有一个满足条件的购买产品,还是要从购买历史中删除不满足条件的购买产品?
-
在您的 tempDataModel 中初始化 customerPurchaseHistory 默认为 nil
-
@Sweeper 我只想拥有满足 tempDataModel 条件的购买历史,我不想更改 dataModel 的数据。换句话说,我想过滤满足条件的数据模型。