Using this Stack Overflow question I have the following code.
let numbers = [1,[2,3]] as [Any]
var flattened = numbers.flatMap { $0 }
print(flattened) // [1,
There may be a better way to solve this but one solution is to write your own extension to Array:
extension Array {
func anyFlatten() -> [Any] {
var res = [Any]()
for val in self {
if let arr = val as? [Any] {
res.append(contentsOf: arr.anyFlatten())
} else {
res.append(val)
}
}
return res
}
}
let numbers = [1,[2, [4, 5] ,3], "Hi"] as [Any]
print(numbers.anyFlatten())
Output:
[1, 2, 4, 5, 3, "Hi"]
This solution will handle any nesting of arrays.