It is also possible to develop a filter function in terms of reduce:
func filterIntermsOfReduce<Element>(elements: [Element], predicate: (Element) -> Bool) -> [Element] {
return reduce(elements: elements, initial: []) {
predicate($1) ? $0 + [ $1 ] : $0
}
}
let result = filterIntermsOfReduce(elements: numbers) { $0 % 2 == 0 }
Again, the result is identical to our previously developed filter function.
In the function body, we provide elements, an empty initial array, and finally, predicate as a combinator.