我有一个简单的功能,根据最后一个编译来自另外两个的字典。
编译器没有显示错误,但执行后resultDict
为空。在调试所有变量counter
时,type.1
和tempDict
具有正确的非零值。
func compileBaseFromCSV(original: [Int:[String]], headers: [Int:String]) -> [Int:[String:[String]]] {
var resultDict = [Int:[String:[String]]]()
var tempDict = [String]()
var counter = 0
for type in headers {
for object in original {
tempDict.append(object.1[type.0])
}
resultDict[counter]?[type.1] = tempDict
counter += 1
}
print(resultDict)
return resultDict
}
这段代码有什么问题?谢谢!
答案 0 :(得分:0)
首先,你从未设置resultDict[counter]
,你需要这样的东西:
if resultDict[counter] == nil {
resultDict[counter] = [:]
}
在将值推入之前。
但是代码中似乎还有一些问题(例如,tempDict应该重置吗?)。使用调试器逐步执行代码并查看值并检查它们的变化(以及它是否符合您的愿望)。