-2

In my particular case I have NSDictionary object which can contain NSString objects as keys and NSString and NSDictionary objects as values. The inner dictionaries can also contain NSDictionary objects.

What if I need to iterate all the inner NSString objects and append a letter to them? Note: I need to change both values and keys

Hamish
  • 78,605
  • 19
  • 187
  • 280
Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
  • 1
    Please at the very least specify whether you're working in Obj-C or Swift. – Hamish May 26 '17 at 10:21
  • @Hamish Does `NSDictionary` behave differently if wrapped in Swift? – Willeke May 26 '17 at 10:37
  • 1
    `NSDictionary` isn't mutable. – Willeke May 26 '17 at 10:44
  • 1
    @Willeke No, but it'll be much more useful for answerers to know what language to answer in (otherwise the question is too vague IMO). And if it is Swift, OP should be using a Swift `Dictionary` and `String` anyway (although this whole data structure of dictionary with values that are either strings or dictionaries sounds a bit odd anyway – it's quite possible that OP should be using a model struct/class instead). – Hamish May 26 '17 at 10:46
  • @Hamish, any language is applicable - I have both languages in my project. Suggest any solution with any language – Vyachaslav Gerchicov May 26 '17 at 10:53
  • Will downvoters finally write what they don't like in my question? – Vyachaslav Gerchicov May 26 '17 at 14:30

1 Answers1

1

In 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)
}

Remember that you can place functions inside of functions in swift. This would all be in one function of its own.

Of course, you could also use flatMap, but that goes at most two layers deep.

As for changing keys, why not set the previous key to nil and then make a new entry in the dictionary?

Alec O
  • 1,697
  • 1
  • 18
  • 31