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

后端 未结 5 1361
礼貌的吻别
礼貌的吻别 2020-12-14 08:51

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]

5条回答
  •  醉梦人生
    2020-12-14 09:19

    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.

提交回复
热议问题