O'Reilly logo

Learning Swift by Andrew J Wagner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Building blocks of functional programming in Swift

The first thing that you should 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.

The filter function

The first function we will discuss is called filter. As the name suggests, this function is used to filter elements in a list. For example, we can filter our number's array to only include even numbers:

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

The closure we provide to the filter will be called once for each element in the array. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required