Latcie Latcie - 5 months ago 6
Swift Question

Simple swift array append not working

I know this is going to be super elementary, but I have this piece of code:

var labels: [String]?

func initVC(image: Images){
self.image = image

let tempLabels = image.label?.allObjects as! [Labels]
for i in 0..<tempLabels.count{
labels?.append(tempLabels[i].label!)
}

}


labels is in the public scope, so the function should have access to it, but when the loop runs through, labels is still nil with no elements.

When I po during debugging, tempLabels is as I expect it to be with 2 string elements.

I'm pretty sure this is a very simple problem, but I guess I'm just out of it right now.

Sam Sam
Answer

Labels has never been initialised. Change

var labels:[String]?

to

var labels:[String] = []