# arrays - index - Swift中的二维数组

## 定义可变数组

``````// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
``````

``````// 2 dimensional array of arrays of Ints
var arr: [[Int]] = []
``````

``````// 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]
``````

``````[
[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])
}
``````

``````class test{
var my2Darr = Int[][]()
}
``````

``````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 arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
``````

``````var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
``````

``````struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
``````

}