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

前端 未结 5 1241
说谎
说谎 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

    Pop the last element and then add it onto the string later:

    let last = myArray.popLast()
    
    let str =  myArray.joinWithSeparator(", ") + " and " + last!
    

    Editing:

        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)
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-16 12:27

    Given an array of String(s)

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

    you can simply write

    let sentence = words.dropLast().joinWithSeparator(", ") + " and " + words.last!
    
    // Apple, Bee, Carrot and Dog
    

    This code needs the words array to contain at least 2 elements to work properly.

    0 讨论(0)
  • 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 + ","
    }
    
    0 讨论(0)
  • 2021-01-16 12:44

    Try this code

        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(", "))
    
        var joinedString : NSString =  myArray.joinWithSeparator(", ")
    
        let lastRangeOfComma = joinedString.rangeOfString(",", options: .BackwardsSearch)
        joinedString = joinedString.stringByReplacingCharactersInRange(lastRangeOfComma, withString: " and")
        print("\(joinedString)")
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题