Swift Dictionary filter()

The filter() method returns all the key-value pairs from the dictionary that satisfies the provided condition.

Example


filter() Syntax

The syntax of the filter() method is:

dictionary.filter({condition})

Here, dictionary is an object of the Dictionary 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 a new dictionary with all the elements from dictionary that satisfy the provided condition

Example 1: Swift dictionary filter()

Output

["Nepal", "Norwegian"]

In the above program, notice the closure definition,

{ $0.key.hasPrefix("K") }

This is a short-hand closure that checks whether all the keys in the dictionary have the prefix "K" 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 dictionary key-value pair is kept
  • false - the dictionary key-value pair is dropped/omitted

And finally, all the elements that start with "N" are stored in the result variable.


Example 2: Return Only Even Values From dictionary

Output

["1st": 2, "3rd": 4]