0

I have a [Any] as the input and would like to know the dimension of the array. For example,

var a = [[[1, 2], [3, 4], [5, 6]]]

The dimension is 3 (3 layer array).

The way I'm using is to use type to convert it to type and count the number of "Array".

"\(type(of: a))" 
$R16: String = "Array<Array<Array<Int>>>"

I wonder is there any better way to achieve my goal.

waitingkuo
  • 89,478
  • 28
  • 112
  • 118
  • 1
    refer : https://stackoverflow.com/questions/33664208/calculate-the-number-of-dimensions-of-a-multi-dimensional-array-in-swift – Piyush Jan 31 '20 at 04:31
  • 5
    Does this answer your question? [Calculate the number of dimensions of a multi-dimensional array in Swift](https://stackoverflow.com/questions/33664208/calculate-the-number-of-dimensions-of-a-multi-dimensional-array-in-swift) – Magnas Jan 31 '20 at 04:55
  • 1
    Try different approach on result of 'a.removeAll()' .-) type(of: ) or Mirror(reflecting: ).subjectType is the only way ... You could play with Mirror, but there is no simpler solution, at least not with public API – user3441734 Jan 31 '20 at 06:11
  • 1
    `extension Collection { var levels: Int { ((first as? [Any])?.levels ?? 0) + 1 } }` – Leo Dabus Jan 31 '20 at 06:19
  • @LeoDabus check with empty multidimensional array ... – user3441734 Jan 31 '20 at 06:22
  • What do you mean by empty multidimensional array? `var a:[Any] = [[]]` returns 2 for me – Leo Dabus Jan 31 '20 at 06:32
  • @LeoDabus var a = [[[1, 2], [3, 4], [5, 6]]] // 3 dimensional array, a.removeAll() , still 3 dimensional array, as reported with type(of:a), but a.levels == 1 – user3441734 Jan 31 '20 at 06:36
  • @LeoDabus var b:[Any] = [[]], b.removeAll() ... STILL THE SAME TYPE! but b.level == 1 – user3441734 Jan 31 '20 at 06:45
  • @LeoDabus let a:[[Any]] = [] is 'two dimensional' with type Array> with .level == 1 – user3441734 Jan 31 '20 at 07:00
  • The real issue is why would you need that. I think you should edit your question and show what is your goal. Forget about array of `Any`. I've been coding in Swift for 5 and a half years and never needed that. – Leo Dabus Jan 31 '20 at 17:33

0 Answers0