这是我的代码:
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
我不明白为什么它在一种情况下会触发我的错误,而在另一种情况下却不会?我认为它会做完全相同的事情......
最佳答案
last
返回最后一个元素,但它不允许您设置新值。事实上,该属性仅实现了 get
:
/// The last element, or `nil` if the array is empty
var last: T? { get }
所以你不能用它来修改数组。
请注意,如果返回的元素是复合值类型(即结构,如数组或字典),则会返回存储在数组中的实际元素的副本。因此,对 last
返回的元素或其任何属性和数据所做的任何更改仅在该副本上执行,而不会影响原始数组。
关于swift - 无法使用 .last 修改多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075358/