Swift Dictionary min()

The min() method returns the minimum key-value pair in the dictionary.

Example

let studentsHeights = ["Sabby": 180.6, "Dabby": 170.3, "Cathy": 156]

// compare the values and return minimum key-value pair let minimumHeight = studentsHeights.min { $0.value < $1.value }
print(minimumHeight!) // Output: (key: "Cathy", value: 156.0)

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

let fruitPrice = ["Grapes": 2.5, "Apricot": 3.5 , "Pear": 1.6]

// compares the values and return minimum key-value pair let minimumPrice = fruitPrice.min { $0.value < $1.value }
print(minimumPrice!)

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

let fruitPrice = ["Grapes": 2.5, "Apricot": 3.5 , "Pear": 1.6]

// compares the keys and return minimum key-value pair let minimumPrice = fruitPrice.min { $0.key < $1.key }
print(minimumPrice!)

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 }