I'm trying to writeWith help from the codereview community, I've written a simple hand-rolled function to flatten a generic nested array. My code works fine as a switch statement, but not when I'm recursively calling it within a "for i in 0..arr.count" loop. I look at each element in the passed in array and say "if this is an array, call the function and pass this in, else appendhave it written several ways but want to focus on the output array".following implementation:
func flatten (input: [Any]) -> [Any] {
var outputArray = [Any] ()
for i in 0..<input.count {
let data = input[i];
(data is Array) ? outputArray += flatten(input: data as! [Any]) : outputArray.append(data)
}
return outputArray
}
Because my function argument must be of type [Any], I'm forced to pass the "data" variable back into it as [data]. This just forces the functionIs there a more "swifty" way to constantly unpack the array and it just gets stuck in the loop. Any suggestions on how I can avoidwrite this without using higher order functions?
The following code works just fineAdditionally, I've been reading about tail call optimization and I honestly can't figure outwonder how to get around my issue -
func flatten (input: [Any]) -> [Any] {
var outputArray = [Any] ()
for e in input {
switch e {
case let e as [Any]:
outputArray += flatten(input: e)
default:
outputArray.append(e)
}
}
return outputArray
}
Edit - figured out working code. Edited above.I can make this tail call optimized?