arrays - Swift:数组中有多少个相同的对象

标签 arrays swift uitableview

我有一个 CollectionView,其中包含诸如...

Fruit(name: String, price: Int, imageUrl: String)

用户可以选择多个 Fruits,然后进行“结帐”,这是一个包含所有已选水果的 UITableViewUITableViewCell 包含:amountLabelfruitLabelpriceLabel

我想在此 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/

相关文章:

c - 根据用户输入的数组添加值

javascript - 在 JavaScript 中动态更新嵌套对象

ios - Facebook SDK 4.0 IOS Swift 以编程方式注销用户

ios - UILabel 上的 UIImage

c - int 数组元素未在 C 中初始化为零

ios - 如何快速将数组保存到 App 的 mainBundle 中的 .plist

swift - 使用 `isSecureTextEntry = true` 测试文本字段时访问 ID 不起作用

ios - FileHandle 在 iOS 中不释放内存

iPhone - UITableViewCell 高度变化的平滑动画,包括内容更新

ios - 当选择单元格时,如何阻止 UIView 的背景颜色消失?