迭代所有内部 NSDictionary 项并更改它们?
Iterate all inner NSDictionary items and change them?
在我的特定情况下,我有 NSDictionary
个对象,它可以包含 NSString
个对象作为键,NSString
和 NSDictionary
个对象作为值。内部字典还可以包含 NSDictionary
个对象。
如果我需要迭代所有内部 NSString
对象并向它们附加一个字母怎么办?注意:我需要同时更改值和键
在Swift中:
func adjustNextLayer(inDictionary dictionary: inout [String:Any], for key: String) {
if let newString = myDictionary[key] as? String {
myDictionary[key] = "\(newString) insert some text to append here"
} else {
If let newDictionary = myDictionary[key] as? [String: Any] {
newDictionary.keys.foreach { key in
adjustNextLayer(inDictionary: newDictionary, for: key}
myDictionary[key] = newDictionary
}
}
}
}
let myDictionary = ["a":1, "b":2]
let keys = myDictionary.keys
keys.foreach { key in
adjustNextLayer(inDictionary: myDictionary, for: key)
}
请记住,您可以在 swift 中将函数置于函数内部。这一切都在它自己的一个功能中。
当然也可以用flatMap,但是最多两层深。
至于改键,为什么不将之前的键设为nil,然后在字典中新建一个条目呢?
在我的特定情况下,我有 NSDictionary
个对象,它可以包含 NSString
个对象作为键,NSString
和 NSDictionary
个对象作为值。内部字典还可以包含 NSDictionary
个对象。
如果我需要迭代所有内部 NSString
对象并向它们附加一个字母怎么办?注意:我需要同时更改值和键
在Swift中:
func adjustNextLayer(inDictionary dictionary: inout [String:Any], for key: String) {
if let newString = myDictionary[key] as? String {
myDictionary[key] = "\(newString) insert some text to append here"
} else {
If let newDictionary = myDictionary[key] as? [String: Any] {
newDictionary.keys.foreach { key in
adjustNextLayer(inDictionary: newDictionary, for: key}
myDictionary[key] = newDictionary
}
}
}
}
let myDictionary = ["a":1, "b":2]
let keys = myDictionary.keys
keys.foreach { key in
adjustNextLayer(inDictionary: myDictionary, for: key)
}
请记住,您可以在 swift 中将函数置于函数内部。这一切都在它自己的一个功能中。
当然也可以用flatMap,但是最多两层深。
至于改键,为什么不将之前的键设为nil,然后在字典中新建一个条目呢?