5

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)

1 Answer 1

5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.