【问题标题】:How to insert values into a nested Swift Dictionary如何将值插入嵌套的 Swift 字典
【发布时间】:2014-08-24 15:11:27
【问题描述】:

我正在尝试在字典中插入新的键值对,它嵌套在另一个 Dictionary:

var dict = Dictionary<Int, Dictionary<Int, String>>()

dict.updateValue([1 : "one", 2: "two"], forKey: 1)
dict[1]?[1] // {Some "one"}

if var insideDic =  dict[1] {
    // it is a copy, so I can't insert pair this way:
    insideDic[3] = "three"
}

dict // still [1: [1: "one", 2: "two"]]

dict[1]?[3] = "three" // Cannot assign to the result of this expression
dict[1]?.updateValue("three", forKey: 3) // Could not find a member "updateValue"

我相信应该是一个简单的方法来处理它,但我花了一个小时仍然无法弄清楚。 我可以改用NSDictionary,但我真的很想了解我应该如何在 Swift 中管理嵌套的Dictionaries

【问题讨论】:

标签: dictionary collections swift


【解决方案1】:

字典是值类型,因此在赋值时被复制。因此,您将不得不获取内部字典(这将是一个副本),添加新键,然后重新分配。

// get the nested dictionary (which will be a copy)
var inner:Dictionary<Int, String> = dict[1]!

// add the new value
inner[3] = "three"

// update the outer dictionary
dict[1] = inner
println(dict) // [1: [1: one, 2: two, 3: three]]

您可以使用ExSwift 等新的实用程序库之一来简化此操作:

dict[1] = dict[1]!.union([3:"three"])

这使用了结合两个字典的union method

【讨论】:

  • 呃……最糟糕的 Swift。我们不应该使用实用程序库来执行此操作。
  • 没错,数组和字典的行为目前正在引起很多的混乱。
  • 谢谢,现在很清楚了。接受这个答案需要认知转变……感觉如此违反直觉。而且我只希望编译器将其优化为尘土,因为在我的实际情况下,这本字典很大。
  • 性能是当前 Swift 状态下的问题,见Swift's Dictionary is slow even with -Ofast
  • @IlyaBelikin 您可以作弊以使其工作 - 与其将字典存储在字典中,不如创建一个充当字典引用的类,并将其存储在您的“外部”字典中!
猜你喜欢
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2019-05-02
  • 2019-11-27
  • 1970-01-01
相关资源
最近更新 更多