0

I'm trying to check whether an object (order of type Order) already exists in an array (newOrderItems - array of Order) before appending it so that I avoid duplicates.

Array declaration:

var newOrderItems = [Order]()

Attempting to delete if exists before appending:

let order = Order(item: item!.name, price: item!.price, quantity: 1, status: "", tags: "", selectedTags: item!.selectedTags, id: item!.id)

if newOrderItems.filter({ $0 == order }).count > 0 {
    newOrderItems.removeAtIndex(newOrderItems.indexOf(order))
}

newOrderItems.append(order!)

The above gives 2 errors:

****** Error 1 ******

Binary operator '==' cannot be applied to operands of type 'Order' and 'Order?'

in line:

if newOrderItems.filter({ $0 == order }).count > 0

****** Error 2 ******

Cannot convert value of type 'Order?' to expected argument type '@noescape (Order) throws -> Bool'

in line:

newOrderItems.removeAtIndex(newOrderItems.indexOf(order))

What am I missing here?


****** EDIT ******

I can get it to work if I rewrite it using a loop:

var counter = 0

for item in newOrderItems {

    if item.id == order?.id {
        newOrderItems.removeAtIndex(counter)
        break
    }
    counter++
}
newOrderItems.append(order!)

2 Answers 2

1

Simple solution to your problem. only replace your

if newOrderItems.filter({ $0 == order }).count > 0

with

if newOrderItems.filter({ $0.id == order.id }).count > 0

Thanks ;]

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

Comments

0

Compare the comparison code in your filter:

if newOrderItems.filter({ $0 == order }).count > 0 { ... }

With that in the while loop:

if item.id == order?.id { ... }

Swift doesn't know how to compare 2 objects of type Order but it knows how to compare 2 Ints (assuming id is of type Int)


Solution

Define an == function for Order:

func ==(lhs: Order, rhs: Order) -> Bool {
    return lhs.id == rhs.id
}

Then you should be able to use filter

if newOrderItems.filter({ $0 == order }).count > 0 {
    newOrderItems.removeAtIndex(newOrderItems.indexOf(order))
}

However, if you want your OrderID to be unique, a Dictionary may be more appropriate.

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.