I have the following array:
var newOrderItems = [Order]()
that holds Order type elements:
let order = Order(item: itemName, quantity: 1)
newOrderItems.append(order!)
At some point newOrderItems holds:
[
Order("item1", 1),
Order("item1", 1),
Order("item2", 1),
Order("item2", 1),
Order("item3", 1),
Order("item1", 1)
]
I need to identify and count duplicate Order array elements so that I form a string message such as:
"You have ordered 3 x item1, 2 x item2, 1 x item3".
Is there a simple way for this? My solution(s) either add way too much overhead (i.e nested loops), or too much complexity (i.e. unique NSCountedSet
) for something that I expect to be trivial.
-
You should use a dictionary not an arrayLeo Dabus– Leo Dabus2016年04月28日 20:05:28 +00:00Commented Apr 28, 2016 at 20:05
3 Answers 3
I would do it with a swift dictionary
to manage orders like :
var newOrderItems = [Order: Int]()
if let order = Order(item: itemName, quantity: 1) {
if newOrderItems[order] == nil {
newOrderItems[order] = 1
} else {
newOrderItems[order]+=1
}
}
And you can print details like :
var str = "You have ordered "
for order in newOrderItems.keys {
str += "\(newOrderItems[order]) x \(order.item),"
}
print(str)
Hopefully it will help!
1 Comment
When you're originally appending the objects to the array, why not increase the counter there, rather than going through after, in order to save time?
1 Comment
how about:
var str = "You have ordered "
for object in newOrderItems {
let itemInstancesFound = newOrderItems!.filter({ 0ドル["item"] as! String == object["item"] as! String }).count
str += "\(itemInstancesFound) x \(object["item"] as! String),"
}
this assumes quantity is always 1 (as showed in my initial Q).