How do you find the maximum value in the Swift dictionary?

So, let's 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] 

How to programmatically find the highest value in a dictionary? Is there a data.max command or something else?

+7
dictionary swift
source share
3 answers
 let maximum = data.reduce(0.0) { max($0, $1.1) } 

Just quickly using reduce .

or

 data.values.max() 

Output:

 print(maximum) // 5.828 
+14
source share

There is a function in the API called maxElement that you can use very simply, which returns the maximum element in self or nil if the sequence is empty and requires strict weak ordering as closure in your case when you use a dictionary. You can use as 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 value, but you can change how you want to use it by keys, it is up to you.

Hope this helps you.

+4
source share

The Swift dictionary provides the max (by :) method. An example from Apple looks like this:

 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))" 
+1
source share

All Articles