我正在尝试创建一个函数,该函数将从“courseInfo”数组及其“courseName”中找到最高的“voteScores”值并将其呈现在我的 viewController 上(仅通过普通的 UILabel - 我可以自己做) .
我如何找到最高的“voteScores”值并获得其“courseName”。
有没有办法在当前数组中对其进行排序?这样我就可以简单地做类似的事情;
highestScoreLabel.text = courseInfo[x].voteScores
或者我必须创建单独的变量吗?
var courseInfo = [ winningCourseInfo(voteScores: 22, courseName: "Course 1"),
winningCourseInfo(voteScores: 34, courseName: "Course 2"),
winningCourseInfo(voteScores: 67, courseName: "Course 3"),
winningCourseInfo(voteScores: 12, courseName: "Course 4")]
最佳答案
swift 1:
func ==(lhs: winningCourseInfo, rhs: winningCourseInfo) -> Bool {
return lhs.voteScores == rhs.voteScores
}
func <(lhs: winningCourseInfo, rhs: winningCourseInfo) -> Bool {
return lhs.voteScores < rhs.voteScores
}
extension winningCourseInfo : Comparable {}
let bestCourse = maxElement(courseInfo)
print(bestCourse.courseName) // "Course 3"
swift 2:
let bestCourse = courseInfo.maxElement { $0.0.voteScores < $0.1.voteScores }
bestCourse?.courseName // "Course 3"
关于arrays - 如何过滤结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491563/