maniponken
maniponken

Reputation: 285

Swift: How many of the same object in array

I have a CollectionView with items like...

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

The user can select multiple Fruits and then proceed to a "checkout" which is a UITableView with all the fruits selected. The UITableViewCell contains: amountLabel, fruitLabel, priceLabel.

I want to show how many of each fruit and the total price is, in this view.

What is the best way to do this?

What I see now :

Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$

total: 16$

What I want to see:

3x Banana - 3$
2x Apple - 4$
3x Orange - 9$

total: 16$

Upvotes: 0

Views: 149

Answers (2)

vadian
vadian

Reputation: 285150

You could group the array and sum up the prices

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)$")

Upvotes: 2

Fogmeister
Fogmeister

Reputation: 77651

This is a perfect case for NSCountedSet.

You can see the documentation for NSCountedSet here.

You can create an NSCountedSet like...

let countedSet = NSCountedSet(array: fruits)

and then get info out of it like...

countedSet.objectEnumerator.forEach {
    let count = countedSet.count(for: $0)

    print($0.name, count, count * $0.price)
}

For your table view you can use countedSet.objectEnumerator.allObjects.count for the number of rows.

Upvotes: 0

Related Questions