Search code examples
iosswiftnsdictionaryplist

Decode Nested Dictionaries in Plist


I have a plist as in screenshot. It fullfills tables and Its cells. I want to get all dictionaries inside "Admin", for example, "FirstTable" "SecondTable" etc.. Below code gives

"Type '(key: Any, value: Any)' doesnot conform to protocol 'Sequence'

error.

if let path = Bundle.main.path(forResource: "Admin", ofType: "plist") {
           myDict = NSDictionary(contentsOfFile: path)
           let admin = myDict?.object(forKey: "Admin") as! NSDictionary
           for dicts in admin{
               for sub_dict in dicts{
                   print(sub_dict)
               }
           }
}

Plist Screenshot


Solution

  • You can't iterate through a dictionary the same way as you iterate through an array. You will have to change

    for dicts in admin {
    

    to

    for (key, value) in admin {
    

    as a dictionary-entry consists of a key and a value and not just a single object like e.g. an array.

    If you want to iterate through all dictionaries you will "need" recursion. If you don't know what that is, it's basically a method that calls itself (but not infinitely). You could do that for example like this:

    func iterateThroughDictionary(dict: Dictionary<String, Any>) {
        for (key, value) in dict {
            if let subDict = value as? Dictionary<String, Any> {
                iterateThroughDictionary(dict: subDict)
            } else {
                print(value);
            }
        }
    }
    

    Then you just have to call it with the root-dictionary.