simlimsd3
simlimsd3

Reputation: 619

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).

How would I find the highest "voteScores" value AND have its "courseName" aswell.

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

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")]

Upvotes: 1

Views: 90

Answers (1)

oisdk
oisdk

Reputation: 10091

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"

Upvotes: 4

Related Questions