【问题标题】:print array in struct in alphabetical order and in descending order按字母顺序和降序打印结构中的数组
【发布时间】:2017-09-02 23:27:43
【问题描述】:

我希望我的结构首先按字母顺序打印其条目,然后按降序排列数据。所以最终的结果是:“lukes 9”、“lukes 4”、“smiths 4”

struct MyData {
    var company = String()
    var score: Int
}

let data = [
    MyData(company: "smiths", score: 4 ),
    MyData(company: "lukes", score: 4),
    MyData(company: "lukes", score: 9)
]

【问题讨论】:

  • 你需要让你的 MyData 符合Comparable

标签: swift sorting struct swift3


【解决方案1】:

有两种方法可以做到这一点。两者都需要您将数组传递给sort(Swift 2),现在是sorted(Swift 3)。

  1. 一个非常简单的实现:

    struct MyData {
        var company = String()
        var score: Int
    }
    
    let data = [
        MyData(company: "smiths", score: 4),
        MyData(company: "lukes", score: 4),
        MyData(company: "lukes", score: 9)
    ]
    
    let sortedArray = data.sorted(by: { ($0.company, $1.score) < ($1.company, $0.score) })
    
  2. 您也可以使MyData 符合Comparable。这将比较逻辑保留在 MyData 类型中,您只需运行 sorted() 函数即可返回一个新数组:

    struct MyData {
        var company = String()
        var score: Int
    }
    
    extension MyData: Equatable {
        static func ==(lhs: MyData, rhs: MyData) -> Bool {
            return (lhs.company, lhs.score) == (rhs.company, rhs.score)
        }
    }
    
    extension MyData: Comparable {
         static func <(lhs: MyData, rhs: MyData) -> Bool {
            return (rhs.company, lhs.score) > (lhs.company, rhs.score)
        }
    }  
    
    let data = [
        MyData(company: "smiths", score: 4),
        MyData(company: "lukes", score: 4),
        MyData(company: "lukes", score: 9)
    ]
    
    let sortedArray = data.sorted()
    

这 2 个实现都输出您想要的结果:“lukes 9”、“lukes 4”、“smiths 4”

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 2017-10-09
  • 2020-08-18
相关资源
最近更新 更多