【问题标题】:How to filter a Model which having nested array in swift如何快速过滤具有嵌套数组的模型
【发布时间】: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 的数据。换句话说,我想过滤满足条件的数据模型。

标签: swift filter append


【解决方案1】:

您的 tempDataModel.customerPurchaseHistory?默认设置为 nil。所以下面的代码不会被执行。

tempDataModel.customerPurchaseHistory?.append(purchaseHistory)

就在你的 for 循环上方,将其值分配给空数组,如下所示:

tempDataModel.customerPurchaseHistory = []

所以,您的代码如下所示:

var dataModel: Consumer360PurchaseHistoryDetails?

var tempDataModel:Consumer360PurchaseHistoryDetails = Consumer360PurchaseHistoryDetails()
tempDataModel.customerPurchaseHistory = []
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

【讨论】:

  • 很高兴为您提供帮助 :)
猜你喜欢
  • 2019-05-22
  • 2017-04-09
  • 2021-11-21
  • 2023-02-19
  • 2015-10-27
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多