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: []) //""