The collections included in Swift allow us the use of higher order functions—that is, functions that take other functions and use them to perform transformations on datasets. For example, an array provides us with the filter
, map
, and reduce
methods.
As previously explained, the preceding code represents an imperative version of array filtering. We can achieve the same goal with a functional approach using the filter
method included in all the types that conform to the SequenceType
protocol. The Array<Element>
struct conforms to the SequenceType
protocol and many other protocols.
Tip
As it happens in most modern languages, Swift supports closures, which are also known as anonymous functions. Closures are self-contained blocks of functionality that we can pass around and use within our code as functions without names. Closures automatically capture everything we reference, such as variables and functions that aren't defined within the closure...