gpt4 book ai didi

ios - 在 Swift 数组的最后一项之前添加单词 "and"

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:00 24 4
gpt4 key购买 nike

我有一个数组中的项目列表。项目的默认输出是以逗号分隔的简单列表。但是,正确的句子应该在列表的倒数第二个和最后一个项目之间包含单词“and”


Swift代码:

    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(", "))

输出:

上面的当前输出是:“Apple, Dog, Carrot, Bee”

但是,正确的输出应该是:“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?

最佳答案

弹出最后一个元素,然后将其添加到字符串中:

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)

关于ios - 在 Swift 数组的最后一项之前添加单词 "and",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39660004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com