John Murcielago John Murcielago - 1 year ago 89
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

is empty. In debug all vars
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 {
resultDict[counter]?[type.1] = tempDict
counter += 1
return resultDict

What's wrong with this code? Thanks!

hnh hnh
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download