Chris Chris - 5 months ago 30
Swift Question

How to insert values into a multidimensional array in a loop swift

Couldnt find the answer to this.

I am trying to insert values into a multi dimensional array with something like this

_ = transportRef.observeEventType(.ChildAdded, withBlock: { (snapshotOne) in

self.yearList.insert(snapshotOne.key, atIndex: 0)

//print("snapshotone.key " + snapshotOne.key) // prints year

if let snapshotTwo = snapshotOne.children.allObjects as? [FIRDataSnapshot] {

for itemTwo in snapshotTwo {

self.monthList[self.counter].insert(itemTwo.key, atIndex: 0)
}
}

counter += 1
}


my
counter
is in another loop outside this one. The thing is I receive an erro
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)
and after playing around in Playground, I realise it is because my
monthList: [[String]] = [[]]
and therefore there isnt any array to insert or something like that. If I were to give it some init like
monthList = [["1"], ["2"]]
then I would be able to insert till
monthList[1]
before it gives an error for
monthList[2]


help? thanks

Answer

You need to provide the inner arrays to store the values into. You could do this by adding a while loop that adds more inner arrays until you have enough to insert to:

for item in itemsOne {
    while counter >= monthList.count {
        monthList.append([String]())
    }
    monthList[counter].insert(item.key, atIndex: 0)
}
Comments