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,453
  • 12
  • 74
  • 129

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
  • 176,635
  • 17
  • 154
  • 256