添加单词“&"和“&".在Swift中数组的最后一项之前 [英] Adding the word "and" before the final item of an array in Swift
问题描述
我有一个数组中的项目列表.项目的默认输出是一个简单列表,以逗号分隔.但是,适当的句子将在列表中倒数第二个和最后一个项目之间包含单词和" .
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.
快捷代码:
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(", "))
输出:
上面的当前输出是:苹果,狗,胡萝卜,蜜蜂"
The current output above is: "Apple, Dog, Carrot, Bee"
但是,正确的输出应该是:苹果,狗,胡萝卜 和 蜜蜂"
However, the proper output should be: "Apple, Dog, Carrot and Bee"
问题:
如何修改代码,以使输出包含单词和" 在列表中的倒数第二个和最后一个项目之间?
How can I modify the code so that the output includes the word "and" between the second last and last item in the list?
推荐答案
弹出最后一个元素,然后稍后将其添加到字符串中:
Pop the last element and then add it onto the string later:
let last = myArray.popLast()
let str = myArray.joinWithSeparator(", ") + " and " + last!
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)
这篇关于添加单词“&"和“&".在Swift中数组的最后一项之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!