1

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?

AnderCover
  • 2,488
  • 3
  • 23
  • 42
Somee
  • 21
  • 6

3 Answers3

3

When you assign to a range of indices in an array (array[1...3]), those elements are removed from the array and the new elements are 'slotted in' in their place. This can result in the array growing or shrinking.

var array = Array(0...5)
// [0, 1, 2, 3, 4, 5]
array[1...3] = [-1, -2]
// [0, -1, -2, 3, 4]

Notice how our array's length is now one element shorter.

Ryan
  • 1,053
  • 12
  • 21
3

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

AnderCover
  • 2,488
  • 3
  • 23
  • 42
  • Thanks, this is exactly what I didn't understand! For some reason I thought that in the range from 1 to 3 every element would change to "bananas" and "oranges", so the array would have two values per index, and that got me confused. It is clear now! – Somee May 13 '21 at 20:11
0

You could use a tuple (Value, Value), or create a struct to handle your values there, in fact if you plan to reuse this pair or value, a struct is the way to go.

By the way, there's no need to add [1..3], just put the values inside the brackets.

struct Value {
    var name: String
    var lastName: String
}

let values = [Value(name: "Mary", lastName: "Queen"), Value(name: "John", lastName: "Black")]

// Access to properties
let lastName = values[1].lastName

// OR

let tuples = [("Mary", "Queen"), ("John", "Black")]

let lastNameTuple = tuples[1].1

Hope you're enjoying Swift!

Andy Nadal
  • 362
  • 3
  • 11