我对Swift中的2D数组感到非常困惑。让我逐步描述。如果我错了,请您纠正我。
首先; 空数组的声明:
class test{ var my2Darr = Int[][]() }
其次,填充数组。(例如my2Darr[i][j] = 0,i,j是for循环变量)
my2Darr[i][j] = 0
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) { ... } */ } }
// 2 dimensional array of arrays of Ints var arr = [[Int]]()
要么:
// 2 dimensional array of arrays of Ints var arr: [[Int]] = []
或者,如果您需要一个预定义大小的数组(如@ 0x7fffffff在评论中所述):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5 var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0)) // ...and for Swift 3+: var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
arr[0][1] = 18
要么
let myVar = 18 arr[0][1] = myVar
arr[1] = [123, 456, 789]
arr[0] += 234
arr[0] += [345, 678]
如果在进行这些更改之前,您有3x2的数组,数组中的数组为0(零),则现在有:
[ [0, 0, 234, 345, 678], // 5 elements! [123, 456, 789], [0, 0] ]
因此请注意,子数组是可变的,您可以重新定义表示矩阵的初始数组。
let a = 0 let b = 1 if arr.count > a && arr[a].count > b { println(arr[a][b]) }
备注: 3维和N维数组的标记规则相同。