ma11hew28
ma11hew28

Reputation: 126319

Join an array of strings with a different final delimiter

Generally: How do I join an array of stings such that the last delimiter is different than the others?

Specifically: How does the iOS Messages app construct the default name of a group conversation, which is a list of contacts' names?

Example

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 (on Rails)

Python

C# (Linq)

Upvotes: 5

Views: 1380

Answers (1)

Casey Fleser
Casey Fleser

Reputation: 5787

Using the class defined in the question you could do something like this:

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

Upvotes: 5

Related Questions