The filter() method returns all the elements from the set that satisfies the provided condition.
Example
var numbers: Set = [2, 3, 6, 9]
// return all the elements greater than 5
var result = numbers.filter({ $0 > 5})
print(result)
// Output: [6, 9]
filter() Syntax
The syntax of the filter() method is:
set.filter(condition)
Here, set is an object of the Set 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 set that satisfies the provided condition
Example 1: Swift set filter()
var languages: Set = ["Swedish", "Nepali", "Slovene", "Norwegian"]
// return all the elements that start with "N"
var result = languages.filter( { $0.hasPrefix("N") } )
print(result)
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 set 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 set value is keptfalse- the set 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 a Set
var numbers: Set = [2, 4, 5, 7, 8, 9]
// check if all elements are even numbers or not
var result = numbers.filter({ $0 % 2 == 0 })
print(result)
Output
[2, 4, 8]