2

How do I create a string from array of objects that have String property?

class Person {
   let name: String
}

let people = [Person(name: "Sam"), Person(name: "Zoey"), Person(name: "Bil")]

let peopleNames: String = //what should be here?

peopleNames = "Sam, Zoey, Bil"
4
  • Did you try this ? stackoverflow.com/a/36488506/2323806 Commented Jun 26, 2018 at 7:22
  • @Vinaykrishnan That is pretty outdated isn't it? It looks like Swift 2. Commented Jun 26, 2018 at 7:24
  • @Sweeper, agreed! At least could get the HINT from the same, and your answer is updated one ;) Commented Jun 26, 2018 at 7:26
  • Possible duplicate of Convert an array of Ints to a comma separated string Commented Jun 26, 2018 at 7:30

1 Answer 1

10

I suppose you want "Sam, Zoey, Bil" as your result?

In that case, you can do this:

people.map { $0.name }.joined(separator: ", ")

We first transform all the people to just their names, then call joined which joins all the strings together.

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

Comments

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.