【问题标题】:How do I filter through an array of Structs?如何筛选结构数组?
【发布时间】:2015-10-08 02:29:39
【问题描述】:

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

【问题讨论】:

    标签: arrays swift struct filter


    【解决方案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"
    

    斯威夫特 2:

    let bestCourse = courseInfo.maxElement { $0.0.voteScores < $0.1.voteScores }
    
    bestCourse?.courseName // "Course 3"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-17
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多