0

I have a tableView with cells of products, and when a cell is selected I want the name of the cell to be added to another array and be separated with "" and ,

The array for the tableView is "a", "b", "c" etc..

var name = ""
var arrayOfNames = ""

tableView

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  tableView.deselectRow(at: indexPath, animated: true)
  name = sections[indexPath.section].productName[indexPath.row]
  arrayOfNames += name
  print(arrayOfNames)
}

So when the cell is pressed it's printing "abc" whereas I want "a", "b", "c"

2 Answers 2

2

You could store the names in an actual array not a string and then use the plain and simple Swift print(_:separator:terminator:)

var array = ["a", "b", "c"]
print(array)
print(array, separator: ", ")
Sign up to request clarification or add additional context in comments.

1 Comment

or array.joined(separator: ", ") which is more generic
0

The problem might be that you’re simply changing the string arrayOfNames by adding each name to it. Therefore, there is no nor , being added. You may want to try:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  tableView.deselectRow(at: indexPath, animated: true)
  name = sections[indexPath.section].productName[indexPath.row]
  if(arrayOfNames == “”) {
nameToAdd = “\”“+ name + “\””
  arrayOfNames += name
} else {
nameToAdd = “, \”“+ name + “\””
  arrayOfNames += nameToAdd
}
  print(arrayOfNames)
}

As you can see there, we are first building a string that contains the name between quotes (and the comma) and then only add it to the final string.

2 Comments

Hi GCourtet, Please add some meaningful explanation along with your code so that the original poster can better understand how your answer solves her/his problem. Thank you.
@Ivan Just did, thanks for letting me know that my answer lacked explanations.

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.