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

前端 未结 5 1294
说谎
说谎 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:19

    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)
    }
    

提交回复
热议问题