简体   繁体   中英

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?

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM