添加单词"和"在Swift

时间:2016-09-23 11:46:53

标签: ios arrays swift string

我有一个数组中的项目列表。这些项的默认输出是一个用逗号分隔的简单列表。但是,正确的句子将在列表中的倒数第二个项和最后一个项之间包含"和#34; 这个词。

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

问题:

  

如何修改代码,使输出包含"和" 这个词   在列表中的倒数第二个和最后一个项目之间?

5 个答案:

答案 0 :(得分:5)

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

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)

答案 1 :(得分:2)

试试此代码

[
    Name:Brian, Count:3, Gross:300, WarrantyCount:2, 
    Name:Kreso, Count:1, Gross:100, WarrantyCount:0, 
    Name:Filip, Count:1, Gross:100, WarrantyCount:1
]

希望这有帮助。

答案 2 :(得分:2)

给定一个String(s)

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

你可以简单地写

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

// Apple, Bee, Carrot and Dog
  

此代码需要words数组包含至少2个元素才能正常工作。

答案 3 :(得分: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)
}

答案 4 :(得分:1)

其中一种可能的方法是使用函数式编程:

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


let mapedArray = myArray.dropLast().map{
    myArray.indexOf($0) == myArray.count - 2 ? $0 + " and " + myArray[myArray.count - 1] : $0 + ","
}