I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.
First of all; declaration of an empty array:
class test{
var my2Darr = Int[][]()
}
Secondly fill the array. (such as my2Darr[i][j] = 0
where i, j are for-loop variables)
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? */
}
}
}
}
And Lastly, Editing element of in array
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))
And you should really upgrade to a newer beta.Int[][]()
is no longer valid syntax. It's been changed to[[Int]]()
.