Arrays 如何过滤结构数组?
我正在尝试创建一个函数,该函数将从courseInfo数组及其courseName中找到最高的voteScores值,并通过一个普通的UILabel将其显示在我的viewController上—我自己也可以这样做 我怎样才能找到voteScores的最高价值,并拥有它的courseName 有没有办法在当前数组中对其进行排序?这样我就可以做一些简单的事情,比如 highestScoreLabel.text=courseInfo[x].voteScores 还是我必须创建单独的变量Arrays 如何过滤结构数组?,arrays,swift,struct,filter,Arrays,Swift,Struct,Filter,我正在尝试创建一个函数,该函数将从courseInfo数组及其courseName中找到最高的voteScores值,并通过一个普通的UILabel将其显示在我的viewController上—我自己也可以这样做 我怎样才能找到voteScores的最高价值,并拥有它的courseName 有没有办法在当前数组中对其进行排序?这样我就可以做一些简单的事情,比如 highestScoreLabel.text=courseInfo[x].voteScores 还是我必须创建单独的变量 var co
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"
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"