【问题标题】:Remove entire element from dictionary从字典中删除整个元素
【发布时间】:2017-11-24 07:53:44
【问题描述】:

我有一本这样的字典...

[

"113": SellerApp.Product(name: "aaaa", id: "113", images: [SellerApp.ProductImage(myId: "996", url: http://myApp.com/public/uploads/products/123_113_1_image_123456789, isDefault: true)], theRate: "234", quantity: "17", sku: "Hdjsu", prdCateg: "tr123", prodDescr: "Gdhd", mrp: "520"), 

"101": SellerApp.Product(name: "dfg", id: "101", images: [SellerApp.ProductImage(myId: "982", url: http://myApp.com/public/uploads/products/563_101_1_image_1011121314, isDefault: true)], theRate: "123", quantity: "7", sku: "345", prdCateg: "tr123", prodDescr: "Test", mrp: "234")

]

现在这些值中的每一个都与一个 tableviewcell 相关联。因此,当我删除特定单元格时,与其关联的所有值都应该被删除。因此,如果我删除第一个单元格,那么在上面的 sn-p 中,从 "113": SellerApp.Product(name: "aa...mrp: "520") 的所有值都应该被删除。

我尝试过这样的事情......

    for (index, dict) in self.appDelegate.myDictionary1.enumerated() {

        if dict.key == (self.appDelegate.commonArrForselectedItems[indexPath.section].id) {

            self.appDelegate.myDictionary1.removeValue(forKey: self.appDelegate.commonArrForselectedItems[indexPath.section].id)

        }
    }

但这似乎会删除 id 本身,并且所有剩余的值都会保留下来。如何从字典中删除与此 ID 关联的所有值..?

【问题讨论】:

  • 为什么在点击索引时不删除tableView的didSelectIndexPath方法中的值?
  • 我的删除方式似乎有些问题......

标签: ios swift nsdictionary


【解决方案1】:

@bvt,尝试删除下面代码中的值

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    yourArrayName.remove(at: indexPath.row)
}

希望它能解决你的问题。

【讨论】:

  • 不..我不想删除整个数组..它只是我要删除的字典元素...
  • Func remove 将 Dictionary.Index 作为参数,而不是 Int.
【解决方案2】:

假设我们的字典是:

var deck = ["Queen": "Spades", "Jack": "Hearts", "King": "Clubs", "Ace": "Diamonds"]

如果我们想删除带有key = "Jack"的元素,我们需要这样写:

let index = deck.index(forKey: "Jack")
deck.remove(at: index!)

按索引删除:

let index = deck.index(deck.startIndex, offsetBy: 2)
deck.remove(at: index)

但是,您应该记住,字典不是有序集合。他们不维护元素的顺序。在我们的示例中,虽然第二个元素是带有key = "King" 的元素,但通过查看代码,经过哈希处理后顺序更改如下:

["Jack": "Hearts", "Ace": "Diamonds", "Queen": "Spades", "King": "Clubs"]

因此,如果你删除第二个元素,"King" : Clubs 的元素不会消失,"Queen": "Spades" 会消失。

【讨论】:

  • 谢谢@Dorukhan Arslan 实际上一切已经正常工作了。调试揭示了这一点。我的错!..:)
猜你喜欢
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 2016-05-06
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
相关资源
最近更新 更多