Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't modify multidimensional array using .last

Here is my code :

var states:[[[Int]]] // I create an empty multidimensional array
states = [[[0,0,0],[0,0,0],[0,0,0]]] // I give it a value


// Why does here it doesn't work ? ('@ivalue $T11' is not identical to 'Int')
states.last![0][0] = 1

// And here it does ?
states[0][0][0] = 1

I am not getting why it triggers me an error in one case and not in the other one ? I thought it would do exactly the same thing...

like image 559
Pop Flamingo Avatar asked Sep 29 '22 09:09

Pop Flamingo


1 Answers

last returns the last element, but it doesn't allow you to set a new value. In fact the property implements the get only:

/// The last element, or `nil` if the array is empty
var last: T? { get }

So you cannot use it to modify the array.

Note that in case the returned element is a composite value type (i.e. a struct, like an array or a dictionary), a copy of the actual element stored in the array is returned. So any change made to the element returned by last or any of its properties and data is performed on that copy only, without affecting the original array.

like image 173
Antonio Avatar answered Oct 13 '22 00:10

Antonio