【发布时间】:2014-09-27 11:01:18
【问题描述】:
我对 Swift 中的二维数组感到非常困惑。让我一步一步描述。如果我错了,请您纠正我。
首先;空数组的声明:
class test{
var my2Darr = Int[][]()
}
第二次填充数组。 (如my2Darr[i][j] = 0其中i,j为for循环变量)
class test {
var my2Darr = Int[][]()
init() {
for(var i:Int=0;i<10;i++) {
for(var j:Int=0;j<10;j++) {
my2Darr[i][j]=18 /* Is this correct? */
}
}
}
}
最后,编辑数组中的元素
class test {
var my2Darr = Int[][]()
init() {
.... //same as up code
}
func edit(number:Int,index:Int){
my2Darr[index][index] = number
// Is this correct? and What if index is bigger
// than i or j... Can we control that like
if (my2Darr[i][j] == nil) { ... } */
}
}
【问题讨论】:
-
你的方法有问题吗?
-
您知道,您的整个第二步可以减少到这个
var my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))并且您真的应该升级到更新的测试版。Int[][]()不再是有效的语法。已改为[[Int]]()。 -
使用重复值的 2D 初始化将不起作用。所有的行都指向同一个子数组,因此不会是唯一可写的。
-
我将一个多维数组包装在一个新结构中以获得更好的 API。