Home > Software design >  How does the function of finding the maximum in the dictionary work?
How does the function of finding the maximum in the dictionary work?

Time:08-28

Please explain to a beginner how the function of finding a maximum in the dictionary works.

I know there are more concise solutions, but I want to understand step by step what is going on here.

var someDictionary = ["One": 41, "Two": 17, "Three": 23]

func maxValue() {

let maxValueOfSomeDictionary = someDictionary.max { a, b in a.value < b.value }
print(maxValueOfSomeDictionary!.value)

}

maxValue()

CodePudding user response:

someDictionary is a Dictionary. A Dictionary is a kind of Sequence (see the "Default Implementations" section of Dictionary to know that it's a Sequence). Sequences provide the method max(by:), which:

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

Swift has trailing-closure syntax, so you can write .max {...} instead of .max(by: { ... }). The two syntaxes are identical, but most developers use trailing-closure syntax when possible.

The parameter is defined as:

areInIncreasingOrder

A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

The Element of Dictionary as a Sequence is a tuple (key: Key, value: Value), so this is the type that is passed to areInIncreasingOrder.

The closure defines two parameters, a and b, each of type (key: Key, value: Value). It returns whether a.value is less than b.value. Swift allows 1-statement closures to omit the return.

This paragraph is somewhat technical and you may want to skip it. The TL;DR is that max returns the maximum element according to your closure. Provided the closure obeys the rules defined in the docs, the max algorithm will return the maximum element, for a specific definition of "maximum," which is that there is no element in the sequence that is ordered after this one according to areInIncreasingOrder. This pedantic definition especially matters when there are incomparables in the list. Equal elements are (somewhat strangely IMO) defined as "incomparable" in that neither is before the other. This also matters for values like NaN.

This will return a maximum element, or nil if the Sequence is empty. (The docs say "the" maximum element, but in the case of incomparable elements, it is not promised which one will be returned.)

maxValueOfSomeDictionary is of type (key: String, value: Int)?, an optional version of the Element of the Dictionary, since it may be a value or it may be nil.

maxValueOfSomeDictionary! converts an Optional into its wrapped value, or crashes if the Optional is nil. This then prints the .value of that.

To see precisely how max operates, you can read the default implementation in stdlib.

  • Related