Swift Dictionary max()

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

Example

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

// compare the values and return maximum key-value pair let maximumHeight = studentsHeights.max { $0.value < $1.value }
print(maximumHeight!) // Output: (key: "Sabby", value: 180.6)

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

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

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

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

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

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

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 }
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges