Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何过滤结构数组?_Arrays_Swift_Struct_Filter - Fatal编程技术网

Arrays 如何过滤结构数组?

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

我正在尝试创建一个函数,该函数将从courseInfo数组及其courseName中找到最高的voteScores值,并通过一个普通的UILabel将其显示在我的viewController上—我自己也可以这样做

我怎样才能找到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"
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"