[英]How do I filter through an array of Structs?
I am trying to create a function that will find the highest "voteScores" value from the "courseInfo" array along with its "courseName" and present it on my viewController (just through a normal UILabel - which I can do myself). 我正在尝试创建一个函数,该函数将从“ courseInfo”数组及其“ courseName”中找到最高的“ voteScores”值,并将其呈现在我的viewController上(仅通过普通的UILabel-我可以自己做)。
How would I find the highest "voteScores" value AND have its "courseName" aswell. 我如何找到最高的“ voteScores”值,并同时获得其“ courseName”。
Is there a way to sort it inside its current array? 有没有办法在其当前数组内对其进行排序? So that I could just simply do something like;
这样我就可以做类似的事情;
highestScoreLabel.text = courseInfo[x].voteScores maximumScoreLabel.text = courseInfo [x] .voteScores
or would I have to create seperate variables? 还是我必须创建单独的变量?
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: 斯威夫特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: 斯威夫特2:
let bestCourse = courseInfo.maxElement { $0.0.voteScores < $0.1.voteScores }
bestCourse?.courseName // "Course 3"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.