Adding the word “and” before the final item of an array in Swift

前端 未结 5 1279
说谎
说谎 2021-01-16 12:08

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\"

5条回答
  •  时光取名叫无心
    2021-01-16 12:39

    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 + ","
    }
    

提交回复
热议问题