Multi dimensional arrays swift with example

An array of the array is also called a matrix, also called a two-dimensional array. You can create multidimensional in multiple ways. It contains multiple sub-arrays based on dimension.

Let’s see some examples of multiple-dimensional arrays.

How to create an empty two-dimensional Array

Arrays can be fixed or dynamic.

Let’s first create an empty two-dimensional array.

The below array contains an array of integers. The first syntax is declared empty with a type declaration on the right side In the second syntax, if you are assigning empty brackets, you need to declare the type

The following ways are to declare a variable with an empty 2nd-dimensional array

  • Use type on the right side
  • using empty square brackets assignment
  • an empty array of value literal syntax
  • Using Array Generics
var matrix = [[Int]]()
var matrix1: [[Int]] = []
var matrix2: [[String]] = [[], [], [],[]]
var matrix3 = Array<Array<Int>>()

Output:

[]
[]
[[], [], [], []]
[]

How to create fixed size two-dimensional array in swift

Or you can declare a fixed array with default values.

Below declare a 3 by 3 array with default values of zero

var matrix3 = Array(repeating: Array(repeating: 0, count: 3), count: 3)
print(matrix3);

Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

How to declare and initialize a two-dimensional array with data

Let’s create a two-dimensional array ie matrix. It contains 2 rows and columns

var matrix2: [[String]] = [[], []]

var rows: [String]=[]
rows.append("one")
rows.append("two")
matrix2[0] = rows

var cols: [String]=[]
cols.append("three")
cols.append("four")
matrix2[1] = cols

print("Matrix: \(matrix2)")
print("rows: \(rows)")
print("cols: \(cols)")

Output:

Matrix: [["one", "two"], ["three", "four"]]
rows: ["one", "two"]
cols: ["three", "four"]

How to append an element into a two-dimensional array in swift?

Let’s declare an array of arrays.

var matrix1: [[Int]] = []

Each element expects an array. Append method is used to append an element. Here

// array of arrays
var matrix1: [[Int]] = []
// add to the matrix
matrix1.append([1,2])
print(matrix1); //[[1, 2]]
// add to the matrix
matrix1.append([3,4])
print(matrix1); //[[1, 2], [3, 4]]

// create a array
var newarray: [Int]=[]
newarray.append(4);
newarray.append(5);
// add to matrix
matrix1.append(newarray) //[[1, 2], [3, 4], [4, 5]]
print(matrix1);

Output:

[[1, 2]]
[[1, 2], [3, 4]]
[[1, 2], [3, 4], [4, 5]]

swift convert the two-dimensional array into one array

Sometimes, We need to convert or flatten two-dimensional arrays into one-dimensional arrays.

Array provides joined method that returns concatenate the sequence of elements and pass this to an array to get

var matrix: [[Int]] = [[1,2],[3,4],[5,6]]
print(matrix);

var oneArray=Array(matrix.joined())
print(oneArray);

Output:

[[1, 2], [3, 4], [5, 6]]
[1, 2, 3, 4, 5, 6]

how to access elements in a 2D Array in Swift

Arrays are always accessed using an index that always starts with zero to the length of an array.

Let’s declare a 2d array with initialized data as follows

var matrix: [[Int]] = [[1,2],[3,4],[5,6]]
print(matrix); // [[1, 2], [3, 4], [5, 6]]

Elements in the normal array can be accessed using the array[index], 2d array can be passed with two indexes, and the second index is optional.

print(matrix[0]);// [1, 2]
print(matrix[1]); //[3, 4]
print(matrix[2]); //[3, 4]
print(matrix[0][0]);//1
print(matrix[0][1]);//2

If an array is accessed with an invalid index i.e. matrix[3] or matrix[0][2] throws an error below

Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range:

How to find the Size of a Multidimensional Array in Swift?

A multidimensional array count is the number of elements in it.

Count function in an array returns only a one-dimensional count, not all elements.

var matrix: [[Int]] = [[1,2],[3,4],[5,6]]
print(matrix); // [[1, 2], [3, 4], [5, 6]]
print("\(matrix.count) ") // 3
print("\(matrix[0].count)") //2

It does not give the correct size of a two-dimensional array.

Use flatMap and get the count as given below

print(matrix.flatMap { $0 }.count) // 6

Looping through a multidimensional array in swift

use nested for loop to iterate an array with the enumerated property as given below

for (i,row) in matrix.enumerated() {
for (j, cell) in row.enumerated() {
print("matrix[\(i),\(j)] = \(cell)")
print("------------------")
}
}

Output:

## matrix[0,0] = 1

## matrix[0,1] = 2

## matrix[1,0] = 3

## matrix[1,1] = 4

## matrix[2,0] = 5

## matrix[2,1] = 6