The min() method returns the minimum key-value pair in the dictionary.
Example
min() Syntax
The syntax of the dictionary min() method is:
dictionary.min {operator}
Here, dictionary is an object of the dictionary class.
min() Parameters
The min() method can take one parameter:
- operator - a closure that accepts a condition and returns a Bool value.
min() Return Value
The min() method returns the minimum element of dictionary.
Note: If dictionary is empty, the method returns nil.
Example 1: Swift dictionary min()
Output
(key: "Pear", value: 1.6)
In the above example, we have passed the closure to find the minimum key-value pair by comparing all the values in fruitPrice. Notice the closure definition,
{ $0.value < $1.value }
This is a short-hand closure that checks whether the first value of fruitPrice is less than the second value or not.
$0 and $1 is the shortcut to mean the first and second parameters passed into the closure.
Since the min() method is optional, we have force unwrapped the optional using !.
Example 2: Compare Keys and Return min Value
Output
(key: "Apricot", value: 3.5)
Here, we have used the key property to compare all the keys of the fruitPrice dictionary
{ $0.key < $1.key }