0

How to flatten an array of Any in Swift 4. Example: Let's suppose I have an array: var array:[Any] = [1, 2, [4, 3], [9, [8, 0]]] and after flatten this array, my expected result is [1, 2, 4, 3, 9, 8, 0]. I try to use flatMap but it didn't work.

lee
  • 7,955
  • 8
  • 44
  • 60
  • 2
    With a little googling.... https://rosettacode.org/wiki/Flatten_a_list#Swift – Ray Toal Oct 15 '17 at 08:19
  • @RayToal: Thanks, this link is so helpful. But could you share with me the `key word` googling to got this result. I just tried but did not got the same result. Just want to improve my search skills :). Thanks so much – lee Oct 15 '17 at 08:52
  • 1
    Ah, I just recognized the operation as "flattening" (from 45 years of programming experience) and the fact that you were flattening arrays within arrays within arrays is "recursive" so I googled "swift flatten list recursively" – Ray Toal Oct 16 '17 at 06:37
  • Thanks so much for sharing. – lee Oct 16 '17 at 07:12

2 Answers2

1

Like Ray Toal suggested (from https://rosettacode.org/wiki/Flatten_a_list#Swift) do

func flatten<T>(_ s: [Any]) -> [T] {
    var r = [T]()
    for e in s {
        switch e {
        case let a as [Any]:
            r += flatten(a)
        case let x as T:
            r.append(x)
        default:
            assert(false, "value of wrong type")
        }
    }
    return r
}

What this function does is the following, it goes over every element in the array and if it finds Int in your case it adds it to the result, if it finds an array of [Any] it calls itself (recursive call) and process repeats until every case gets to the inner most Int. Result is then returned at the end. Notice the asset that will be thrown if your array is not Ints and array of Ints ([Int])

Then you can do:

var array:[Any] = [1, 2, [4, 3], [9, [8, 0]]]
array = flatten(array)
//result [1, 2, 4, 3, 9, 8, 0]
Ladislav
  • 7,223
  • 5
  • 27
  • 31
0

Try to use reduce and joined functions of Array.

var array:[Any] = [1, 2, [4, 3], [9, [8, 0]]]

   var flatArray = array.reduce([],+]

else 

   var flatArray = Array(array.joined())
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
  • both of them didn't work for me. I got the error with `reduce` : `Ambiguous reference to member '+'` – lee Oct 15 '17 at 08:22
  • With `joined` I got the error `Ambiguous reference to member 'joined()'`. I use `Xcode9.1 beta2 Playground ` – lee Oct 15 '17 at 08:23