Higher Order Functions in Swift 2
Where you have a nested array that simply needs joining with an additional array of values placed between each use
join()
. If you have an array that needs to be flattened and needs additional values appended as a suffix or prefix to each nested array useflatMap()
. If you require a one off initial value and possibly to append values before or after nested values usereduce()
.[…]
The focus of this post has been arrays, but actually there are things that can be done with dictionaries as well.
Update (2015-07-27): Natasha Murashev:
In other words,
flatMap
is specifically overloaded to deal with Optionals. It will take an array of optionals and return an array of unwrapped optionals without any nils.[…]
The idea of thinking of
flatMap
as dealing with containers vs just arrays makes things a lot clearer!
Update (2015-09-25): Giovanni Lodi:
A good use case for
map
andflatMap
in the context ofOptional
is to simplify code usingif let
s.