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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.