Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple swift array append not working

Tags:

arrays

swift

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.

like image 715
Latcie Avatar asked Jun 24 '16 00:06

Latcie


People also ask

How to add String to an array of String in Swift?

To append a string to the String array in Swift, use the function append() on the array. Following is a quick example to add a string value to the array using append() function. After appending, the size of the array increases by 1.

What is array in Swift?

Specifically, you use the Array type to hold elements of a single type, the array's Element type. An array can store any kind of elements—from integers to strings to classes. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.


2 Answers

Labels has never been initialised. Change

var labels:[String]?

to

var labels:[String] = []
like image 111
Sam Avatar answered Oct 14 '22 08:10

Sam


You are declaring the labels variable but never allowing it to store information. This means that it does not necessarily exist, since it is not initialized, and therefore cannot be used.

For it to be useable, you must initialize it

var labels:[String] = []
like image 28
GJZ Avatar answered Oct 14 '22 07:10

GJZ