我有一个 CollectionView,其中包含诸如...
Fruit(name: String, price: Int, imageUrl: String)
用户可以选择多个 Fruits
,然后进行“结帐”,这是一个包含所有已选水果的 UITableView
。
UITableViewCell
包含:amountLabel
、fruitLabel
、priceLabel
。
我想在此 View 中显示每种水果的数量和总价。
最好的方法是什么?
我现在看到的:
Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$
total: 16$
我想看到的:
3x Banana - 3$
2x Apple - 4$
3x Orange - 9$
total: 16$
最佳答案
您可以对数组进行分组并对价格求和
let grouped = Dictionary(grouping: fruits, by: {$0.name})
var total = 0
for (key, value) in grouped {
let price = value.reduce(0, {$0 + $1.price})
print(value.count, key, "\(price)$")
total += price
}
print("total: \(total)$")
关于arrays - Swift:数组中有多少个相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338155/