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 .j av  a  2 s  .  co m*/
         (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(
    {//from   w  w  w  .ja  v  a 2  s  . c o  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)/*from   ww w .  j  av a  2  s. c o m*/

Result

Related Example