Swift Set filter()

The filter() method returns all the elements from the set that satisfies the provided condition.

Example


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()

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 kept
  • false - 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

Output

[2, 4, 8]