Имея:
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)])
Поскольку вы используете класс, вы можете избежать удобства инициализации и просто добавить сумму.