Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Swift Dictionary filter()
In this tutorial, we will learn about the Swift dictionary filter() method with the help of examples.
The filter() method returns all the key-value pairs from the dictionary that satisfies the provided condition.
Example
var marks = ["Sabby": 89, "Dabby": 45, "Cathy": 74]
// return all the key-value pair with value greater than 50
var result = marks.filter({ $0.value > 50})
print(result)
// Output: ["Cathy": 74, "Sabby": 89]
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()
var age = ["Kyle": 7, "Eric": 9, "Kenny": 10]
// return all key-value pairs with value that start with "K"
var result = age.filter( { $0.key.hasPrefix("K") } )
print(result)
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 keptfalse- 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
var numbers = ["1st": 2, "2nd": 7, "3rd": 4, "4th": 5]
// check if all values are even numbers or not
var result = numbers.filter({ $0.value % 2 == 0 })
print(result)
Output
["1st": 2, "3rd": 4]