swift - 无法使用 .last 修改多维数组

标签 swift multidimensional-array

这是我的代码:

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/

相关文章:

Swift SpriteKit 初始化程序错误不断出现

php - 通过键数组创建嵌套数组

c - 如何访问指针结构中的字符串?

php - 在多维数组中查找最小/最大值

swift - 你如何在 Swift 字典中找到最大值?

ios - 合并中的音频不起作用

ios - 在 viewDidAppear 中以编程方式更改为 Tabbar 选项卡 View

php - PHP 中使用一个特定键从数组中提取值的通用函数

c 中多维数组的编译器错误

ios - Swift - base64EncodingStringWithOptions 不工作 Xcode 6.1