一般情况下:如何加入一系列叮咬,使最后一个分隔符与其他分隔符不同?
具体来说:iOS Messages应用程序如何构建群组对话的默认名称,这是联系人姓名列表?
实施例
class User {
var name: String
init(name: String) {
self.name = name
}
}
let users = [
User(name: "Matthew"),
User(name: "Mark"),
User(name: "Luke"),
User(name: "John")
]
users.list(" & ") { $0.name } // => "Matthew, Mark, Luke & John"
PHP
Ruby(在Rails上)
的Python
C#(Linq)
答案 0 :(得分:4)
使用问题中定义的类,您可以执行以下操作:
let names = users.map { $0.name }
let suffix = names.suffix(2)
let joined = (names.dropLast(suffix.count) + [suffix.joinWithSeparator(" & ")]).joinWithSeparator(", ")
print(joined) // prints Matthew, Mark, Luke & John