Swift - Array filter(): filter the elements inside an array and return a subset of the elements

Introduction

The array filter() function returns another array containing a subset of the original elements that satisfy the specified criteria.

The following code shows how to apply a filter to the array to return all those elements greater than 20:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var pricesAbove20 = prices.filter (
     {/*  w  w  w . ja va 2s .  com*/
         (price:Double) -> Bool in
             price>20
     }
)
print(pricesAbove20)

Result

The filter() function takes a closure.

The closure itself accepts a single argument representing each element of the original array, and returns a Bool result.

The closure is called once for every element in the array.

The result will contain the element if the statement (price>20 ) evaluates to true.

Using type inference, the code can be reduced as follows:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]
var pricesAbove20 = prices.filter(
    {// w  w w  . j  ava  2s .co m
          (price) in
            price>20
     }
)
print(pricesAbove20)

Result

Eliminating the named parameters yields this:

Demo

let prices = [12.0,45.0,23.5,78.9,12.5]

var pricesAbove20 = prices.filter( { $0>20 } )
print(pricesAbove20)/*www .j a  va2s.c  o  m*/

Result

Related Example