【问题标题】:add data using a loop in 2d dictionary in swift 2.2在 swift 2.2 中使用 2d 字典中的循环添加数据
【发布时间】:2016-11-17 16:00:04
【问题描述】:

我声明了一个二维字典,如下所示:

var dic:NSDictionary = [Int:[String:String]]()

现在,我想使用循环在二维字典中插入数据。我坚持这样做

示例字典视图是

dic[0]
      - key value
      - key value
dic[1]
      - key vlaue
      - key value 
dic[2]
      - key value
      - key value

【问题讨论】:

  • 你到底有什么问题?
  • 你可以添加你尝试过的代码
  • @AMomchilov 实际上我想使用循环在二维字典中添加键和值,我得到了一些答案,让我尝试一下,但如果你有比这些答案更好的解决方案,请建议我... ..谢谢

标签: ios swift macos swift2


【解决方案1】:

正如 vacawama 在他的回答中提到的,没有理由不坚持使用原生 Swift 类型:使用 Dictionary 而不是 NSDictionary。这个答案提供了一种使用嵌套字典的替代方法。

可选的链接和字典方法updateValue(_:forKey:)

您可以使用DictionaryupdateValue(_:forKey:) 方法来设置或更新特定键的值。我不确定您所说的“循环中”是什么意思,但下面是一个使用updateValue(_:forKey:) 构建外部字典和内部字典(这里是虚拟字典)的示例

var dict = [Int:[String:String]]()

for outerKey in (0...3) {
    // reset/create a new inner dictionary
    dict.updateValue([:], forKey: outerKey)
    
    // update/add new key-value pair of inner dict
    for dummyKeyValuePairs in (1...2) {
        dict[outerKey]?.updateValue("Value\(dummyKeyValuePairs)",
                                    forKey: "Key\(dummyKeyValuePairs)")
    }
}

print(dict)
/* [2: ["Key1": "Value1", "Key2": "Value2"], 
    0: ["Key1": "Value1", "Key2": "Value2"], 
    1: ["Key1": "Value1", "Key2": "Value2"], 
    3: ["Key1": "Value1", "Key2": "Value2"]] */

如果您想在您的内部字典中添加(或编辑)另一个键值对,只需使用updateValue(_:forKey:),就像上面一样:

dict[2]?.updateValue("NewValue", forKey: "NewKey")
   /*   \
       note that this optional chaining here means our
       updating/adding of inner dictionary key-value pairs
       is entirely performed as a side effect, where we
       never make use of the actual result of the expression */

print(dict)
/* [2: ["Key1": "Value1", "Key2": "Value2", "NewKey": "NewValue"],
    0: ["Key1": "Value1", "Key2": "Value2"],
    1: ["Key1": "Value1", "Key2": "Value2"],
    3: ["Key1": "Value1", "Key2": "Value2"]] */

W.r.t.您关于如何打印字典的键值对的问题,例如,您可以应用嵌套的for ... in 方法:

for (outerKey, innerDict) in dict {
    print("Key-value pairs for outer dict key \(outerKey) follows:")
    for (key, value) in innerDict {
        print("\tkey: \(key), value: \(value)")
    }
}
/*  Key-value pairs for outer dict key 2 follows:
        key: Key2, value: Value2
        key: Key1, value: Value1
    Key-value pairs for outer dict key 0 follows:
        key: Key2, value: Value2
        key: Key1, value: Value1
    Key-value pairs for outer dict key 1 follows:
        key: Key2, value: Value2
        key: Key1, value: Value1
    Key-value pairs for outer dict key 3 follows:
        key: Key2, value: Value2
        key: Key1, value: Value1                  */

请注意,字典是无序集合,因此在上面打印时输出无序。

【讨论】:

  • 感谢您的帮助,但如果我想打印那些 2d dict 数据,该怎么做?我使用like : for i in 0..
  • @Helper 我编辑了答案以包含一个如何打印字典内容的示例。如果唯一的目的是打印 all 字典的内容,我通常会避免明确的“索引”(/key)访问自己。如果您希望对内容进行排序,您可能需要重新考虑使用字典(替代方案:元组数组)。
  • 非常感谢它的工作......但是为什么索引未排序,我的意思是为什么它是前 2 为什么不是 0
  • @Helper 乐于提供帮助。我在回答的最后一句话中提到了这一点:字典是无序集合,这意味着它们以键值对的形式保存内容,但它们没有这些内容的顺序。如果顺序对您很重要,您最好使用不同的数据结构,例如具有元组值的数组。
【解决方案2】:

我建议您在字典中坚持使用 Swift 类型,而不是使用 NSDictionary。如果你创建一个 [Int:[String:String]] 字典,你可以将它传递给一个接受 NSDictionary 的例程,但你会得到 Swift 类型系统的所有优点。

当您插入多级字典时,您需要确保内部字典存在,然后再尝试向其添加值。我使用了 nil 合并运算符 ?? 来获取内部字典。如果dict[key1]返回nil,那么就没有key对应的内部字典,所以用[:]创建一个字典。

var dict = [Int:[String:String]]()

func insert(inout dict: [Int:[String:String]], key1: Int, key2: String, value: String) {
    var inner = dict[key1] ?? [:]
    inner[key2] = value
    dict[key1] = inner
}

insert(&dict, key1: 1, key2: "hair", value: "brown")
print(dict)
[1: ["hair": "brown"]]
insert(&dict, key1: 1, key2: "eyes", value: "green")
print(dict)
[1: ["eyes": "green", "hair": "brown"]]
insert(&dict, key1: 0, key2: "hair", value: "black")
print(dict)
[0: ["hair": "black"], 1: ["eyes": "green", "hair": "brown"]]

【讨论】:

  • 你能帮助我如何使用循环执行此操作并再次使用循环打印数据......谢谢。
  • 编辑您的问题以显示您希望在字典中插入的一些数据。第一个键 0、1、2 代表什么?插入数据时如何知道使用哪个键?
猜你喜欢
  • 1970-01-01
  • 2012-06-16
  • 2017-08-23
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多