Equatable not detecting the difference between two objects of the same class

159 Views Asked by At

I have an item of the class Product. I'm changing a variable within the Product class but my addToCart method below treats the item as if no changes have been made. I'm comparing the products based on the id and the variationId. What am I doing wrong?

import UIKit

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
    }
}

The user can select a different color for the product and in doing so changes the variationId.

The addItemToCart() method checks if the cartItems array contains this product. If the product exists, the quantity gets increased by 1 otherwise the product is added to the array.

var cartItems = [Product]()

func addItemToCart(product: Product) {
    if cartItems.contains(product) {
        let quantity = product.quantity
        product.quantity = quantity + 1
    } else {
        cartItems.append(product)
    }
}

The method above keeps updating the quantity regardless if the variationId is different or not.

2

There are 2 best solutions below

0
On

You can do this as follows, you can also remove the equatable attribute.

var cartItems = [Product]()

func addItemToCart(product: Product) {
    if let cardItemIndex = cardItems.firstIndex(where: { $0.id == product.id && $0.variationId == product.variationId}) {
        cartItems[cardItemIndex].quantity += 1
    } else {
        cardItems.append(product)
    }
}
1
On

You are not updating the correct object. Your addItemToCart(product:) function should be something like this:

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