Cannot 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 don’t understand why this causes an error in one case and not in another? I thought this would do the same ...

+5
source share
1 answer

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

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

Therefore, you cannot use it to modify an array.

Note that in case the returned item is a composite value type (i.e., a structure, such as an array or a dictionary), a copy of the actual item stored in the array is returned. Therefore, any change made to the element returned by last or any of its properties and data is performed only for this copy, without affecting the original array.

+4
source

Source: https://habr.com/ru/post/1207466/


All Articles