如何从具有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"
Run Code Online (Sandbox Code Playgroud)
Swe*_*per 10
我想你想要"Sam, Zoey, Bil"的结果呢?
在这种情况下,您可以这样做:
people.map { $0.name }.joined(separator: ", ")
Run Code Online (Sandbox Code Playgroud)
我们首先将所有人转换为他们的名字,然后调用joined将所有字符串连接在一起.
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |