To create a Two Dimensional Array in Swift, you can use an array of arrays.
In this example,
matrix
with dimensions 3x3.var matrix = Array(repeating: Array(repeating: 0, count: 3), count: 3)
for i in 0..<matrix.count {
for j in 0..<matrix[i].count {
matrix[i][j] = i + j
}
}
print(matrix)
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
In this example,
matrix
with dimensions 2x2.var matrix = Array(repeating: Array(repeating: "", count: 2), count: 2)
for i in 0..<matrix.count {
for j in 0..<matrix[i].count {
matrix[i][j] = "Row \(i + 1), Column \(j + 1)"
}
}
print(matrix)
[["Row 1, Column 1", "Row 1, Column 2"], ["Row 2, Column 1", "Row 2, Column 2"]]
In this tutorial, we learned How to create a Two Dimensional Array in Swift language with well detailed examples.