Swift Functional Programming: filter

December 27th, 2017

Filed under: iOS Development, Mac Development | Be the first to comment!

I’m learning about functional programming in Swift. To sharpen my understanding I’m writing about what I’ve learned. I start with the filter function.

The filter Function

As its name indicates, the filter function filters out the elements of a collection that don’t meet a condition. The filter function operates on a collection, such as an array, using a closure (a function without a name) that returns a Boolean value. filter returns the elements in the collection that return true from the closure.

Suppose you have an array of test scores, and you want to get the passing test scores. Test scores of 60 or higher pass. The following code demonstrates how to get the passing scores using filter:

let testScores = [78, 96, 48, 65, 55, 91]
let passingScores = testScores.filter {
    $0 >= 60

What the code does is take each item in the testScores array and check if it’s greater than or equal to 60. If the item is greater than or equal to 60, it is added to the passingScores array.

If you look at the value of passingScores, it has the following values:

[78, 96, 65, 91]

filter Lets You Write Less Code

A big advantage of using the filter function is less code to write. If you were to get the passing scores without filter, you would have to write something similar to the following code:

let testScores = [78, 96, 48, 65, 55, 91]
var passingScores: [Int] = [ ]

for score in testScores {
    if score >= 60 {

What Is $0?

Looking at the code for the filter example, you might be wondering what $0 is. The $0 expression represents the first argument in the closure, which is the current element in the array in my filter example. It’s the equivalent of the score variable in the code sample that doesn’t use filter.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *