Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Plist中解码嵌套字典_Ios_Swift_Nsdictionary_Plist - Fatal编程技术网

Ios 在Plist中解码嵌套字典

Ios 在Plist中解码嵌套字典,ios,swift,nsdictionary,plist,Ios,Swift,Nsdictionary,Plist,我有一张截图。它填充表格及其单元格。我想把所有字典都放在“Admin”里面,例如,“FirstTable”“SecondTable”等等。。下面的代码给出 “类型”(键:任意,值:任意)不符合协议“序列” 错误 if let path = Bundle.main.path(forResource: "Admin", ofType: "plist") { myDict = NSDictionary(contentsOfFile: path) let ad

我有一张截图。它填充表格及其单元格。我想把所有字典都放在“Admin”里面,例如,“FirstTable”“SecondTable”等等。。下面的代码给出

“类型”(键:任意,值:任意)不符合协议“序列”

错误

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

不能像遍历数组一样遍历字典。 你必须改变

for dicts in admin {

因为字典条目由键和值组成,而不是像数组这样的单个对象

如果你想遍历所有的字典,你将“需要”递归。如果你不知道那是什么,它基本上是一个调用自身(但不是无限)的方法。 您可以这样做,例如:

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);
        }
    }
}
func迭代字典(dict:Dictionary){
用于dict中的(键、值){
如果let subct=值为?字典{
迭代字典(dict:subct)
}否则{
印刷品(价值);
}
}
}

然后你只需要用根字典调用它。

这样我只能访问FirstTable、SecondTable等。我如何才能访问单元格中的?cell-1、cell-2等。它在我的情况下不起作用,因为例如对于thirdtable,它只有两个字符串,所以它没有任何字典。在你的函数中,所有字典都需要有相同的c我猜有很多字典。不,它们没有。该函数将“打开”一个字典。然后它将遍历其中的所有条目。如果条目是另一个字典,它将打开该字典并遍历其所有条目,依此类推。这将适用于(几乎)无限嵌套的字典。如果一个条目是一个字符串,那么你可以对它做任何你想做的事情。为什么你只使用字典?而不是
cell-1,-2,-3
First-,Second-,ThirdTable
数组更合适,因为与字典不同,它们有特定的顺序。在Swift 4中,你可以使用
PropertyListDecoder
将plist直接解码为结构。您能给我一个更详细的示例吗?我需要将FirstTable更改为array吗?
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);
        }
    }
}