Reputation: 482
I have array of custom objects
var shopList = [String: [ShopItem]]()
Custom class
class ShopItem {
var id = ""
var name = ""
var quantity = 0.0
var price = 0.0
var category = ""
init(id: String, name: String, quantity: Double, price: Double, category: String) {
self.id = id
self.name = name
self.quantity = quantity
self.price = price
self.category = category
}
var uom: String {
return "шт."
}
var total: Double {
return quantity * price
}
}
What is right way to remove object from array? I tried to do it way below
extension ShopItem: Equatable {}
func ==(left: ShopItem, right: ShopItem) -> Bool {
return left.id == right.id
}
But as you see I got error :(
Upvotes: 0
Views: 39
Reputation: 285150
Due to value semantics (objects are copied rather than referenced) the value
object is immutable. Even if you assign value
to a variable the object is not removed in the shopList
dictionary.
You need to remove the object directly in the dictionary (the code is Swift 3)
func removeItem(item: ShopItem) {
for (key, value) in shopList {
if let index = value.index(of: item) {
shopList[key]!.remove(at: index)
}
}
}
Upvotes: 1