0

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.

1
  • You should use a dictionary not an array Commented Apr 28, 2016 at 20:05

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

That would require Order to conform to protocol Hashable
0

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

I'd need multiple counters since different types of order items can increase / decrease infinitely (theoretically).
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.