我有自定义对象数组
var shopList = [String: [ShopItem]]()
自定义类
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
}
}
从数组中删除对象的正确方法是什么? 我试着在下面这样做
extension ShopItem: Equatable {}
func ==(left: ShopItem, right: ShopItem) -> Bool {
return left.id == right.id
}
但是当你看到我收到错误时:(
答案 0 :(得分:1)
由于值语义(对象被复制而不是被引用),value
对象是不可变的。即使您将value
分配给变量,也不会在shopList
字典中删除该对象。
您需要直接在字典中删除对象(代码是Swift 3)
func removeItem(item: ShopItem) {
for (key, value) in shopList {
if let index = value.index(of: item) {
shopList[key]!.remove(at: index)
}
}
}