Christian Dietrich Christian Dietrich - 5 months ago 22
Swift Question

Flatten a Array of Arrays in Swift

Is there a counterpart in Swift to

flatten
in Scala, Xtend, Groovy, Ruby and co?

var aofa = [[1,2,3],[4],[5,6,7,8,9]]
aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9]


of course i could use reduce for that but that kinda sucks

var flattened = aofa.reduce(Int[]()){
a,i in var b : Int[] = a
b.extend(i)
return b
}

Answer

There's no flatten method in the Swift's default functions. Checkout ExSwift, it implements flatten as an extension on Array.

Edit:

I'm aware that this answer has collected so many negative votes. It was written less than a month after Swift was announced, and nobody really knew much about it. We now have a flatMap method in the standard library. So we can use it to flatten an Array of Arrays:

array.flatMap { $0 }
Comments