The filter() method returns all the elements from the array that satisfy the provided condition.
Example
filter() Syntax
The syntax of the filter() method is:
array.filter(condition)
Here, array is an object of the Array class.
filter() Parameters
The filter() method takes one parameter:
- condition - a closure that accepts a condition and returns a Bool value.
filter() Return Value
- returns all the elements from the array that satisfy the provided condition
Example 1: Swift Array filter()
Output
["Nepal", "Norwegian"]
In the above program, notice the closure definition,
{ $0.hasPrefix("N") }
This is a short-hand closure that checks whether all the elements in the array have the prefix "N" or not.
$0 is the shortcut to mean the first parameter passed into the closure.
The closure returns a Bool value depending upon the condition. If the condition is
true- the array value is keptfalse- the array value is dropped/omitted
And finally, all the elements that start with "N" are stored in the result variable.
Example 2: Return Only Even Numbers From Array
Output
[2, 4, 8]