vee
vee

Reputation: 739

Issue with appending and referencing

Hi im having an issue with the following two lines of code below. Im trying to insert an item from items array to the checkout array and set its stock to 1. However, it is also setting the stock to 1 for the items array. Can someone explain why?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let item = items[indexPath.item]
    //inventoryController?.showItemDetailForItem(item: item, index: indexPath.item)
    if item.stock != 0 {
        total += item.price //adding each item to cart adds its price to the checkout price
    for x in checkout {
        if item.name == x.name{
            print("before stock is \(item.stock)")
            x.stock += 1
            print("after stock is \(item.stock)")
            return
        } else{
            print("not equal")
        }
    }
        checkout.insert(item, at: 0) // THIS IS WHERE THE ISSUE IS
        checkout[0].stock = 1 //THIS IS WHERE THE ISSUE IS
    } else{
        print("Not enough stockempty")
    }
    print("stock is \(item.stock)")
    collectionView.reloadData()
}

Upvotes: 0

Views: 43

Answers (1)

vadian
vadian

Reputation: 285082

item is obviously a class. A class is a reference type.

When you are going to append a reference type object to a collection type, only a pointer will be assigned and the reference counter of the original object will be incremented.

So changing the value of a property affects all occurrences of the item.

To prevent this behavior use a value type (a struct) or make a copy of the object

Upvotes: 1

Related Questions