Swift 4.x
To add a bit more flatMap to the array, if there is an array containing an array of arrays, then flatMap not actually work.
Assume an array
var array:[Any] = [1,2,[[3,4],[5,6,[7]]],8]
Which returns flatMap or compactMap :
array.compactMap({$0}) //Output [1, 2, [[3, 4], [5, 6, [7]]], 8]
To solve this problem, we can use our simple looping logic + recursion
func flattenedArray(array:[Any]) -> [Int] { var myArray = [Int]() for element in array { if let element = element as? Int { myArray.append(element) } if let element = element as? [Any] { let result = flattenedArray(array: element) for i in result { myArray.append(i) } } } return myArray }
So call this function with the given array
flattenedArray(array: array)
Result:
[1, 2, 3, 4, 5, 6, 7, 8]
This function will help smooth any array, given the case of Int here
Exit on the playground: 
Rajan Maheshwari Jul 23 '18 at 12:22 2018-07-23 12:22
source share