Creating a functional version of array filtering

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 Sequence protocol. The Array<Element> struct conforms to the Sequence protocol and many other protocols. In Swift versions prior to 3, the Sequence protocol was named SequenceType.

Tip

As it happens in most modern languages, Swift supports ...

Get Swift 3 ObjectOriented Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.