Search code examples
nsstringiterationnsdictionarymutable

Iterate all inner NSDictionary items and change them?


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


Solution

  • 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?