Functional Methods

Note

Open Functional.playground at the Methods page.

Note

The following sections show different ways of performing the same tasks. They say nothing about which version, if any, is better.

filter

The filter method looks like this:

func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

This is a simple method on Sequence, which we have already used. The input function takes an element of the sequence and returns either false or true. filter returns an array of only those elements for which the input function returns true:

let numbers = [-4,4,2,-8,0]
let negative =   numbers.filter {$0<0} // [-4, -8]

Set and Dictionary have their own versions of this method, which return a Set or Dictionary, respectively.

Using the filter ...

Get Beginning Swift 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.