Print the key of the max value from a dictionary Swift

Viewed 34

I am learning to code in Swift and I have an exercise that I am trying to improve. What I want to do is be able to print the Key that has the highest value from the dictionary. I know how to check the highest value and print that, but not the key. Any ideas or suggestions on how to print it?

Thank you everyone for your time!

//Dictionary to store the the person and the score generated
var studentsAndScores = ["Pedro": Int.random(in: 0...100), "Juan": Int.random(in: 0...100), "Alicia": Int.random(in: 0...100)]

//Select the higher of the values from the Dictionary
var largest = studentsAndScores.values.max()

//Print the score that everyone get and the higher score
print("The score for Pedro is \(studentsAndScores["Pedro"]!)")
print("The score for Juan is \(studentsAndScores["Juan"]!)")
print("The score for Pedro is \(studentsAndScores["Alicia"]!)")
print("The higher score is \(largest!)")
1 Answers

Dictionary has a max(by:) method:

studentsAndScores.max { lhs, rhs in
    lhs.value < rhs.value
}
Related