Swift开发中如何打印字典内最大值对应的Key
问题
我正在学习Swift编程,目前正在优化练习代码,想要实现的功能是打印字典中存储最大值对应的Key。我目前已经掌握了查找并打印字典最大值的方法,但不知道如何获取该最大值对应的Key,希望能得到相关实现思路或建议。
原有代码
//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"]!)") // 此处存在笔误:提示文案写了Pedro,实际取的是Alicia的分数 print("The higher score is \(largest!)")
实现方案
不需要单独提取字典values找最大值再反查key,Swift字典原生支持直接对键值对做比较,一次遍历就能拿到目标结果,有两种常用实现方式:
方式1:获取单个最大值对应的Key(最简洁高效)
使用字典自带的max(by:)方法,传入value的比较规则,直接返回值最大的键值对元组,时间复杂度O(n),只需要遍历一次字典。var studentsAndScores = ["Pedro": Int.random(in: 0...100), "Juan": Int.random(in: 0...100), "Alicia": Int.random(in: 0...100)] // 比较两个键值对的value,拿到分数最高的学生数据 guard let topEntry = studentsAndScores.max(by: { $0.value < $1.value }) else { // 字典为空的异常处理 print("无有效学生分数数据") exit(0) } // 遍历打印所有学生分数,避免硬编码名字写错 for (name, score) in studentsAndScores { print("The score for \(name) is \(score)") } print("The higher score is \(topEntry.value), the student who got the highest score is \(topEntry.key)")注意:如果字典中有多个相同的最大值,这个方法会返回遍历过程中第一个遇到的最大值对应的键值对。
方式2:获取所有最大值对应的Key
如果存在多个并列最高分的场景,可以先拿到最大值,再过滤出所有值等于最大值的Key:var studentsAndScores = ["Pedro": Int.random(in: 0...100), "Juan": Int.random(in: 0...100), "Alicia": Int.random(in: 0...100)] guard let highestScore = studentsAndScores.values.max() else { print("无有效学生分数数据") exit(0) } // 过滤所有分数等于最高分的学生名字 let topStudentNames = studentsAndScores.filter { $0.value == highestScore }.map(\.key) for (name, score) in studentsAndScores { print("The score for \(name) is \(score)") } print("The highest score is \(highestScore), students who got this score: \(topStudentNames.joined(separator: ", "))")
额外提示:原代码里硬编码每个学生名字打印分数的写法很容易出现笔误(你原代码里第三个打印就把Alicia的提示文案写成了Pedro),直接遍历字典键值对打印可以完全避免这类问题。
内容的提问来源于stack exchange,提问作者Pedro
相关产品推荐
相关产品推荐

