Building blocks of functional programming in Swift

The first thing to realize is that Swift is not a functional programming language. At its core, it will always be an object-oriented programming language. However, since functions in Swift are first-class citizens, we can use some of the core techniques. Swift provides some built-in methods to get us started.

Filter

The first method we are going to discuss is called filter. As the name suggests, this method is used to filter elements in a list. For example, we can filter our numbers array to include only even numbers:

var evenNumbers = numbers.filter({ element in
    element % 2 == 0
}) // [2, 4]

The closure we provide to filter will be called once for each element in the array. It is tasked with returning ...

Get Swift: Developing iOS Applications 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.