0

I have an array of string like this

let arrayOfString = ["Nancy", "Peter", "Kevin"]

and I want to join all array elements together with a comma and a space separating in between.

let joinResult = arrayOfString.joined(separator: ", ")

which gives me

Nancy, Peter, Kevin

my question is if it is possible to add the word "and" before the last element if array.count > 2. In this case, it will be

Nancy, Peter, and Kevin
//if arrayOfString = ["Nancy"], only shows Nancy with no comma and space

Thanks!

Code
  • 6,041
  • 4
  • 35
  • 75
Nancy P
  • 57
  • 5

2 Answers2

0

Here is a solution

let arrayOfString = ["Nancy", "Peter", "Kevin"]

let joinedString = arrayOfString.dropLast().joined(separator: ", ")
                   + (arrayOfString.count > 1 ? " and " : "")
                   + (arrayOfString.last ?? "")

print(joinedString)   //Nancy, Peter and Kevin

You could also define the above as a function

func joinedNames(from array: [String]) -> String {
    return array.dropLast().joined(separator: ", ")
           + (array.count > 1 ? " and " : "")
           + (array.last ?? "")
}

and test it like so:

joinedNames(from: ["Nancy", "Peter", "Kevin"])  //"Nancy, Peter and Kevin"
joinedNames(from: ["Nancy", "Peter"])           //"Nancy and Peter"
joinedNames(from: ["Nancy"])                    //"Nancy"
joinedNames(from: [])                           //""

If you need the Oxford comma here is the solution:

func joinedNamesWithOxfordComma(from array: [String]) -> String {
    return array
        .enumerated()
        .map {(index, element) in
            if index == 0 {
                return element
            } else if index <= array.count - 2 {
                return ", " + element
            } else if array.count > 2 {
                return ", and " + element
            } else {
                return " and " + element
            }
        }.joined()
}

joinedNamesWithOxfordComma(from: ["Nancy", "Peter", "Kevin"])  //"Nancy, Peter, and Kevin"
joinedNamesWithOxfordComma(from: ["Nancy", "Peter"])           //"Nancy and Peter"
joinedNamesWithOxfordComma(from: ["Nancy"])                    //"Nancy"
joinedNamesWithOxfordComma(from: [])                           //""
ielyamani
  • 17,807
  • 10
  • 55
  • 90
0

Here's a safe approach

let names = ["Nancy", "Peter", "Kevin"]

func join(names: [String], separator: String, lastSeparator: String) -> String? {
    guard !names.isEmpty else { return nil }
    guard names.count > 1 else { return names.first }
    return names
        .dropLast()
        .joined(separator: separator) + " " + lastSeparator  + " " + names.last!
}

join(names: names, separator: ",", lastSeparator: "and")

Result

"Nancy,Peter and Kevin"
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148