John Murcielago John Murcielago - 4 months ago 15
Swift Question

Populating dictionary in Swift

I've got a simple function which compiles a dictionary from two others according to the last.
Compiler shows no errors, but after execution

resultDict
is empty. In debug all vars
counter
,
type.1
and
tempDict
have correct not-nil values.

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
}


What's wrong with this code? Thanks!

hnh hnh
Answer

For one, you never set resultDict[counter], you need something like:

if resultDict[counter] == nil {
  resultDict[counter] = [:]
}

before pushing values into it.

But there seem to be a few more issues in your code (e.g. should tempDict get reset?). Use the debugger to step through your code and look at the values and check how they change (and whether that matches your desire).