是否有任何有效的方法来组合对象数组?我有一个模型 [sales]
,它有 saleAmount, soldBy
。不同的客户可能会出售多种商品。所以我想要的是,如果元素由 ABC 销售,那么我想对 ABC 销售的 saleAmount 求和。下面给出了一个例子。
class Sale {
var soldBy : String = ""
var saleAmount : Double = 0.00
}
var sales : [sale] = [sale]()
sales array contains:
[
["ABC", 1200.34],
["ABC", 999.34],
["ABC", 3499.99],
["DEF", 333.32],
["DEF", 778.12]
]
Expected output :
[["ABC", 5699.67],
["DEF" , 1111.44]]
最佳答案
拥有:
struct Sales {
let name: String
let amount: Float
init(name: String, amount: Float) {
self.name = name
self.amount = amount
}
}
我会补充:
extension Sales {
init(withSales initialSales: Sales, otherSale: Sales) {
self.init(name: initialSales.name, amount: initialSales.amount + otherSale.amount)
}
}
我将使用reduce(into:_:)
:
let sales: [Sales] = [Sales(name: "ABC", amount: 1200.34),
Sales(name: "ABC", amount: 999.34),
Sales(name: "ABC", amount: 3499.99),
Sales(name: "DEF", amount: 333.32),
Sales(name: "DEF", amount: 778.12)]
let reducedSale = sales.reduce(into: [Sales]()) { (currentResult, current) in
if let existingSalesIndex = currentResult.firstIndex(where: { $0.name == current.name }) {
let existingSale = currentResult[existingSalesIndex]
currentResult[existingSalesIndex] = Sales(withSales: existingSale, otherSale: current)
} else {
currentResult.append(current)
}
}
print("reducedSales: \(reducedSales: [AppName.Sales(name: "ABC", amount: 5699.67), AppName.Sales(name: "DEF", amount: 1111.44)])
因为你使用类,你可以避免方便的初始化,而只是添加数量。
关于ios - 俱乐部对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336801/