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

后端 未结 5 1362
礼貌的吻别
礼貌的吻别 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-14 09:34

    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))"
    
    0 讨论(0)
  • 2020-12-14 09:38

    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.

    0 讨论(0)
  • 2020-12-14 09:42
    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
    
    0 讨论(0)
提交回复
热议问题