13

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.

3 Answers 3

37

Labels has never been initialised. Change

var labels:[String]?

to

var labels:[String] = []
Sign up to request clarification or add additional context in comments.

1 Comment

it's always the littlest things that are so time consuming. thanks again!
3

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] = []

1 Comment

Careful with your language, because this is not technically correct. The labels variable is actually never created and that is where the issue in this question first arrises. He has declared labels as an optional variable, meaning it may or may not be created at the point of use. The variable itself doesn't actually exist until it is initialised, until then it is just a declaration
-7

Yep, it was super simple.

Changed

var labels: [String]?

To

var labels = [String]()

1 Comment

If you are happy with a response, click on the green tick next to it: that shows that the answer you chose solved your problem. If you would like to add more details, please do that in the question, not in a separate answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.