So, say I have a dictionary that looks like this:
var data : [Float:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201]
Exist a function in the API, named maxElement you can use it very easy , that returns the maximum element in self
or nil
if the sequence is empty and that requires a strict weak ordering as closure in your case as you use a Dictionary. You can use like in the following example:
var data : [Float:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201]
let element = data.maxElement { $0.1 < $1.1} // (.0 8, .1 5.828)
And get the maximum value by the values, but you can change as you like to use it over the keys, it's up to you.
I hope this help you.
There are two methods to find max value in the dictionary.
First approach:
data.values.max
Second approach:
data.max { $0.value < $1.value}?.value
If you want to find max key:
data.max { $0.key < $1.key}?.key
A Swift Dictionary provides the max(by:) method. The Example from Apple is as follows:
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional(("Heliotrope", 296))"
Honestly the solutions mentioned above - work, but they seem to be somewhat unclear to me as a newbie, so here is my solution to finding the max value in a Dictionary using SWIFT 5.3 in Xcode 12.0.1:
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()
After the dot notation (meaning the ".") put max and the code inside {} (curly braces) to compare the components of your Dictionary.
let maximum = data.reduce(0.0) { max($0, $1.1) }
Just a quick way using reduce
.
or:
data.values.max()
Output:
print(maximum) // 5.828