Wednesday, July 22, 2015

Higher Order Functions in Swift 2

Anthony Levings:

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 use flatMap(). If you require a one off initial value and possibly to append values before or after nested values use reduce().

[…]

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 and flatMap in the context of Optional is to simplify code using if lets.

Comments RSS · Twitter

Leave a Comment