1

I have a list of items in an array. The default output of the items is a simple list separated by commas. However, a proper sentence would include the word "and" between the second last and last item in the list.


Swift code:

    let myItem1: String = "Apple"
    let myItem2: String = "Bee"
    let myItem3: String = "Carrot"
    let myItem4: String = "Dog"

    let myArray = Set(arrayLiteral: myItem1, myItem2, myItem3, myItem4)

    //print("Item count:", myArray.count)
    print("Item list:", myArray.joinWithSeparator(", "))

Output:

The current output above is: "Apple, Dog, Carrot, Bee"

However, the proper output should be: "Apple, Dog, Carrot and Bee"


Question:

How can I modify the code so that the output includes the word "and" between the second last and last item in the list?

James Monger
  • 10,181
  • 7
  • 62
  • 98
user4806509
  • 2,925
  • 5
  • 37
  • 72
  • 2
    Remove the last item, join with `, ` as you do now. Add _and_ & last item. – Desdenova Sep 23 '16 at 11:57
  • Related: [Join an array of strings with a different final delimiter](http://stackoverflow.com/questions/39496725/join-an-array-of-strings-with-a-different-final-delimiter) – Hamish Sep 23 '16 at 12:58
  • 1
    Unrelated: Why is your set of strings named `myArray`? Also you should never have to use the `init(xyzLiteral:)` initialisers directly, they're meant for the compiler to use. In this case you can just do `let mySet : Set = [myItem1, myItem2, myItem3, myItem4]` – Hamish Sep 23 '16 at 13:02
  • Thanks for the advice @Hamish. I guess `myArray` is better explained as `mySet`. `arrayLiteral` was used because Xcode suggested it and was retuning an error prior to that. – user4806509 Sep 23 '16 at 13:44

6 Answers6

5

Pop the last element and then add it onto the string later:

let last = myArray.popLast()

let str =  myArray.joinWithSeparator(", ") + " and " + last!

Editing:

    let myItem1: String = "Apple"
    let myItem2: String = "Bee"
    let myItem3: String = "Carrot"
    let myItem4: String = "Dog"

    let mySetArray = Set(arrayLiteral: myItem1, myItem2, myItem3, myItem4)

    var myArray = Array(mySetArray)

    let last = myArray.popLast()

    let str =  myArray.joinWithSeparator(", ") + " and " + last!
    print(str)
Bista
  • 7,869
  • 3
  • 27
  • 55
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
2

Try this code

    let myItem1: String = "Apple"
    let myItem2: String = "Bee"
    let myItem3: String = "Carrot"
    let myItem4: String = "Dog"

    let myArray = Set(arrayLiteral: myItem1, myItem2, myItem3, myItem4)

    //print("Item count:", myArray.count)
    print("Item list:", myArray.joinWithSeparator(", "))

    var joinedString : NSString =  myArray.joinWithSeparator(", ")

    let lastRangeOfComma = joinedString.rangeOfString(",", options: .BackwardsSearch)
    joinedString = joinedString.stringByReplacingCharactersInRange(lastRangeOfComma, withString: " and")
    print("\(joinedString)")

Hope this helps.

nishith Singh
  • 2,968
  • 1
  • 15
  • 25
2

Given an array of String(s)

let words = ["Apple", "Bee", "Carrot", "Dog"]

you can simply write

let sentence = words.dropLast().joinWithSeparator(", ") + " and " + words.last!

// Apple, Bee, Carrot and Dog

This code needs the words array to contain at least 2 elements to work properly.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
2

You can now just do

ListFormatter.localizedString(byJoining: names)

This gives

Apple, Bee, Carrot and Dog

buildsucceeded
  • 4,203
  • 4
  • 34
  • 72
1
var arrNames:[String] = ["Apple","Bee","Carrot","Dog"];
var allNames:String!


override func viewDidLoad() {
    super.viewDidLoad()

    allNames = arrNames[0]

    for i in 1...arrNames.count-1{
        if i == arrNames.count - 1 {
            allNames = allNames + " and " + arrNames[i]
        }else{
            allNames = allNames + ", " + arrNames[i]
        }
    }

    print(allNames)
}
user4806509
  • 2,925
  • 5
  • 37
  • 72
Bista
  • 7,869
  • 3
  • 27
  • 55
1

One of the possible ways is to use functional programming:

let myArray = ["Apple", "Bee", "Carrot", "Dog"]


let mapedArray = myArray.dropLast().map{
    myArray.indexOf($0) == myArray.count - 2 ? $0 + " and " + myArray[myArray.count - 1] : $0 + ","
}
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100