该代码打印字典中的最高分数。我怎样才能打印第二最高分。我想打印前2名的分数。打印排名前2的最高成绩
import UIKit
var people: [[String:Any]] = [
[
"firstName": "Sam",
"lastName": "Newton",
"score": 13
],
[
"firstName": "Joe",
"lastName": "Mckenzie",
"score": 23
],
]
var topPerson = people[0]
var bestScore = topPerson["score"] as! Int
var bestScore1 = topPerson["score"] as! Int
for person in people {
if let score = person["score"] as? Int {
if bestScore < score {
bestScore = score
topPerson = person
}
}
}
if let first = topPerson["firstName"] as? String,
let second = topPerson["lastName"] as? String {
print("\(first) \(second)")
}
按“分数”对字典数组进行排序,然后打印数组中的前两个元素。 – DonMag
排序总是一个选项,但是如果您只需要前2个元素,您也可以执行相同的循环,但只需忽略下一次运行中最顶端的输入。 – xander
@DonMag的分选解决方案是一个很好的解决方案。请下次使用正确的缩进使您的代码更具可读性 –