{

How to get or return top 5 elements from an Array swift with example


An array of the array is also called a matrix, also called a two-dimensional array. You can create multi-dimensional 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 multi-dimensional 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
------------------
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.