icaksama icaksama - 23 days ago 10
iOS Question

IOS - How to catch dynamic array dimension from JSON in Swift 3

Hello everyone I need help. I have JSON with dynamic array dimension value. This is the example :

//array 1 dimension
"array_dimension" : 1, //we can change to 2 dimension or more
"my_array" : [0, 1, 2, 3, 4] //the value adjust with array_dimension

//array 2 dimension
"array_dimension" : 2,
"my_array" : [[0, 1, 2], [3, 4], [5]]

//array 3 dimension
"array_dimension" : 3,
"my_array" : [[[0, 1], [2]], [[3], [4]], [[5]]]


And now I only can catch the my_array value in variable with static array dimension like this :

//example value in array 2 dimension
"array_dimension" : 2,
"my_array" : [[0, 1, 2], [3, 4], [5]]

//Program to catch my_array value in Swift 3
if let my_array = myJSON["my_array"] as? [[Int]] {
var myArray: [[Int]]?
myArray = my_array
} else {
print("\(TAG) error : JSON parsing my_array not found")
}


How can I catch all dynamic array dimension from my_array value in a variable (Swift 3) ?

UPDATE :
How I can use that technique ?

Answer

Your array is not Array<Int>, your array is Array<Any>.

Inside application you know how deep arrays in your root array. Based on that, you can take "last" meta array, that contains Int values (with type Array<Any>). After that you can get element by index and use:

let value : Int = Null;
if let intElement = array[index] as? Int {
   value = intElement;
}
else
{
   print("Error with element type (print element)");
}