Codementor Events

FlatMap Swift

Published Dec 20, 2017

As the name suggests this function will flatten a the collection of collections.

let collections = [[1,2,3],[4,5],[6,7,8]]
let flat = collections.flatMap { $0 }
print(flat)//[1, 2, 3, 4, 5, 6, 7, 8]

You can even chain both flatmap and filter functions on a collection.

For example you can filter odd numbers from collection of collections.

let collections = [[1,2,3],[4,5],[6,7,8]]
let oddValues = collections.flatMap { $0.filter{ $0 % 2 != 0} }
print(oddValues)//[1, 3, 5, 7]Start writing here...
Discover and read more posts from saikiran
get started
post commentsBe the first to share your opinion
Show more replies