【问题标题】:Removing from complex custom array从复杂的自定义数组中移除
【发布时间】:2017-06-06 17:13:07
【问题描述】:

我有一组自定义对象

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
}

但是如你所见,我得到了错误:(

【问题讨论】:

标签: arrays swift


【解决方案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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-04-03
    • 2021-04-08
    • 2021-10-17
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多