Search code examples
swiftswift4

Array with multiple values per index?


I'm learning swift, and I do the sololearn course to get some knowledge, but I bumped into something that I don't understand.
It is about modifying an array's values. The questionable part states the following:

In the following example, the elements with index 1, 2, 3 are replaced with two new values.

shoppingList[1...3] = [“Bananas”, “Oranges”] 

How can an one dimensional array take more than one value per index? And how do I access them? Am I misunderstanding something?


Solution

  • What this code does is replacing the element of shoppingList in the 1...3 range using Array.subscript(_:)

    That means considering this array:

    var shoppingList = ["Apples", "Strawberries", "Pears", "Pineaples"]
    

    that with:

    shoppingList[1...3] = ["Bananas", "Oranges"]
    
    

    Strawberries, Pears and Pineaples will be replaced by Bananas and Oranges.

    so the resulting array will be: Apples, Bananas, Oranges