Matthieu Riegler
Matthieu Riegler

Reputation: 55554

Flatten and unwrap optionals in Double dimensional array

The following code does the job.

var array:[[Int?]] = [[1,2,3,nil],[1,2,3,nil]]
var flattened = array.flatMap{$0}.flatMap{$0}
// flattened is of type [Int] 

But two flatMap one after another doesn't make the code easily readable if find. How would you write this in a cleaner way ?

Upvotes: 2

Views: 229

Answers (1)

Martin R
Martin R

Reputation: 539965

flatMap<S : SequenceType>(transform: (Self.Generator.Element) throws -> S) rethrows -> [S.Generator.Element] is a combination of map() and flatten():

s.flatMap(transform)
is equivalent to
Array(s.map(transform).flatten())

You are using flatMap() with the "identity transform" { $0 } to concatenate the arrays; this can be simplified by using flatten() directly:

let flattened = array.flatten().flatMap { $0 }

Upvotes: 2

Related Questions