Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] 

How would I programmatically find the highest value in the dictionary? Is there a "data.max" command or something?

like image 469
Sunay Avatar asked Feb 05 '16 20:02

Sunay


People also ask

How do you find the highest number in Swift?

To find the largest number in an array in Swift, call max() method. max() method returns the maximum of the elements present in the array.

How do you find the maximum and minimum of a dictionary?

The easiest way to find the minimum or maximum values in a Python dictionary is to use the min() or max() built-in functions applied to the list returned by the dictionary values() method.

How do you return a max value in a dictionary?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

What is Max in Swift?

max() Return Value The max() method returns the maximum element of dictionary . Note: If dictionary is empty, the method returns nil .


2 Answers

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 
like image 96
Eendje Avatar answered Nov 16 '22 01:11

Eendje


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))" 
like image 32
Narsail Avatar answered Nov 15 '22 23:11

Narsail