如何从具有String属性的对象数组中创建字符串?
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"
答案 0 :(得分:10)
我想您希望将"Sam, Zoey, Bil"
作为结果?
在这种情况下,您可以这样做:
people.map { $0.name }.joined(separator: ", ")
我们首先将所有人换成他们的名字,然后调用joined
,它将所有字符串连接在一起。