Swift class does not retain the value in one of its properties

77 Views Asked by At

I have multiple items of the class Product. I'm comparing the products based on the id and the variationId.

class Product: Equatable {
    let id: Int
    let name: String
    var variationId: Int
    var quantity: Int
    
    init(id: Int, name: String, variationId: Int, quantity: Int) {
        self.id = id
        self.name = name
        self.variationId = variationId
        self.quantity = quantity
    }
    
    static func == (lhs: Product, rhs: Product) -> Bool {
        return
            lhs.id == rhs.id && lhs.variationId == rhs.variationId
    }
}

In the product view controller I have a struct VariationOption and a variable product as follows.

struct VariationOption {
    var id: Int
    var name: String
    var option: String
}

var product: Product!

When the user changes the color option, it changes the variationId property for that product

self.product.variationId = variationOption.id

The user can select a different color for the product and in doing so changes the variationId. When adding the product to the cart, the addItemToCart function checks if the product exists in the shopping cart. If the product exists, the quantity for that product id changes, otherwise the product gets added to the cart.

What I'm trying to do is compare the variation id and if it is different also add the product to the cart.

The problem I'm having is this. The user selects an option, the variation id changes, the product is being added to the cart but instead of adding a new product it is changing the variation id to the product already in the cart products array.

How can I make sure the product inside the products array in the shopping cart does not change the variation id property?

func addItemToCart(product: Product) {
    if let cartItemIndex = cartItems.firstIndex(of: product) {
        cartItems[cartItemIndex].quantity += product.quantity
    } else {
        cartItems.append(product)
    }
}
0

There are 0 best solutions below