O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

Filter

The filter algorithm will return a new array by filtering the original array. This is one of the most powerful array algorithms and may end up as the one you use the most. If you need to retrieve a subset of an array based on a set of rules, I recommend using this algorithm rather than trying to write your own method to filter the array.

The closure takes one argument, and it should return a Boolean true if the element should be included in the new array, as shown in the following code:

var arrayOne = [1,2,3,4,5,6,7,8,9] 
let filtered = arrayOne.filter{$0 > 3 && $0 < 7} 
//filtered contains 4,5 and 6 

In the preceding code, the rule that we are passing to the algorithm returns true if the number is greater than 3 and less than 7; therefore, ...

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