The filter
function takes a function that, given an element in array, returns Bool,
indicating whether the element should be included in the resulting array. The filter
method is declared as follows in Swift standard library:
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
The definition is similar to the map
method with the following differences:
- The
filter
function takes a closure that receives elements of itself and returns aBool
value - The result of the
filter
method will be an array of its own type
Let's examine the following code to understand how it works:
let numbers = [10, 30, 91, 50, 100, 39, 74] let evenNumbers = numbers.filter { $0 % 2 == 0 }
The resulting evenNumbers
array will be [10, 30, 50, 100, 74]
.
Let's implement the filter
function ourselves. In fact, its implementation is going to be similar to the implementation of map
, except that it does not require a second generic specifying the codomain. Instead, it conditionally...