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?

2
  • 1
    Use Tuple for each index. stackoverflow.com/a/25838682/14733292 Commented May 13, 2021 at 18:22
  • 3
    What the code above does is the same as replaceSubrange method where you replace any number of elements with another collection. Commented May 13, 2021 at 18:26

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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.

Comments

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!

2 Comments

Thanks for your examples! But I'm still curious if the example given by SoloLearn makes any sense just by itself?
No need for any tuples, the code in the question works fine as it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.