We are creating a global struct where we store our products for a shopping cart. Here is the code to create it
class Cart : NSObject {
var allProductsInCart = [Product]()
class var sharedCart: Cart {
struct Static {
static let instance = Cart()
}
return Static.instance
}
}
In a separate view controller (called ProductVC), we are creating an instance of Product. We add that product to the array listed above, allProductsInCart like this and then change the value:
let newProduct = Product()
newProduct.name = "Costco"
Cart.sharedCart.allProductsInCart.append(newProduct)
newProduct.name = "test2"
print ("value is: \(Cart.sharedCart.allProductsInCart[0].name)") //It prints "test2" not "Costco"
When the separate instance of product is modified in ProductVC, it is also changed in the struct. It is definitely a separate instance of product because it has a different variable name as seen above.
It should print Costco still because the instance of Product within the ProductVC was modified after it was added to the struct and we want to print the instance in the struct. Right? Or do I have something wrong?
Is this normal behavior? Is there a reason this is happening? Is there a better way that a global variable is supposed to be created or a better way to create a sharedCart that we can access in any view controller?