4

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)

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

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
Casey Fleser
  • 5,707
  • 1
  • 32
  • 43