arrays - 如何过滤结构数组?

标签 arrays swift struct filter

我正在尝试创建一个函数,该函数将从“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/

相关文章:

swift - 将记录保存到 CloudKit 时应用程序崩溃

ios - visibleCells 返回 tableViewCell 中 collectionView 中的所有单元格

C中结构的构造函数

c - 删除记录二进制文件c

go - 如何从 Go 中的另一个包导入结构

c - 访问其他大小的 32 位字数组

javascript - 如何在数组中声明多个具有不同上下文(ctx)的CANVAS?

swift - 您只能将计算变量与 setter 和 getter 一起使用来覆盖父类(super class)的存储属性

C# 比较字符串值数组

C编程101 : Dice game Assignment that adds an extra turn when players roll a 6