正如 vacawama 在他的回答中提到的,没有理由不坚持使用原生 Swift 类型:使用 Dictionary 而不是 NSDictionary。这个答案提供了一种使用嵌套字典的替代方法。
可选的链接和字典方法updateValue(_:forKey:)
您可以使用Dictionary 的updateValue(_: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 */
请注意,字典是无序集合,因此在上面打印时输出无序。