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"
Luda
  • 7,282
  • 12
  • 79
  • 139

1 Answers1

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313