Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.

I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.

var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)

2

The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.

In Matlab this is a simple task with the following line of code,

a = [1,2,3;3,4,5]
size(a)
ans =
2 3

Is there a simple equivalent in Swift

I have looked high and low for a solution and cant seem to find exactly what i am after.

Thanks
- HB

like image 949
Harry B Avatar asked Jan 13 '18 10:01

Harry B


People also ask

What is the size of multidimensional array?

Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.

How do I get the size of an array in Swift?

Swift – Array Size To get the size of an array in Swift, use count function on the array. Following is a quick example to get the count of elements present in the array. array_name is the array variable name. count returns an integer value for the size of this array.

How do you create a multidimensional array in Swift?

In Swift, creating a multi-dimensional array is just a matter of adding another set of brackets. For example, to turn our [String] array into an array of arrays, you would just write [[String]] .

What is 2D array in Swift?

With special syntax in Swift, we create multidimensional arrays. We nest brackets—2 or more levels of nesting can be used. An initialization syntax is also available. Array info.


1 Answers

Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.

let arr = [
    [1,2,3,4,5],
    [1,2,3],
    [2,3,4,5],
]

So the concept of "rows" and "columns" does not exist. There's only count.

If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:

arr.flatMap { $0 }.count

If you are sure that your array is a matrix, you can do this:

let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
like image 113
Sweeper Avatar answered Sep 20 '22 15:09

Sweeper