0

I'm trying to extract values out of an array and concatenate all the values in one string like the following

var ingredient: String

for tag in tags {
   if let text = tag.titleLabel?.text {
      ingredient += " \(text)"
   }
}

recipe.ingredients = ingredient

But I Xcode complains:

Variable "ingredient" passed by reference before being initialized

I think it complains that ingredient is initialized but has no value to start with for concatenation. Is that right? How can I achieve what I want?

0

1 Answer 1

1
recipe.ingredients = tags.flatMap { $0.titleLabel?.text }.joinWithSeparator(" ")

Not exactly the same, but this way it's safe and in one line.

Sign up to request clarification or add additional context in comments.

2 Comments

This turns out to be exactly what I wanted. I think my approach was failing and will fail 99% because it won't have value until user put some value, is that right? I'm just trying to learn :)
To be exact, it will fail 100% :). Basically, you can't use the variable before it is initialized.

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.