Swift Dictionary max()

The max() method returns the maximum key-value pair in the dictionary.

Example


max() Syntax

The syntax of the dictionary max() method is:

dictionary.max {operator}

Here, dictionary is an object of the dictionary class.


max() Parameters

The max() method can take one parameter:

  • operator - a closure that accepts a condition and returns a Bool value.

max() Return Value

The max() method returns the maximum element of dictionary.

Note: If dictionary is empty, the method returns nil.


Example 1: Swift dictionary max()

Output

(key: "Apricot", value: 3.5)

In the above example, we have passed the closure to find the maximum 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 max() method is optional, we have force unwrapped the optional using !.


Example 2: Compare Keys and Return max Value

Output

(key: "Pear", value: 1.6)

Here, we have used the key property to compare all the keys of the fruitPrice dictionary

{ $0.key < $1.key }