在struct中按字母顺序和降序打印数组

时间:2017-09-02 23:27:44

标签: swift sorting struct swift3

我希望我的结构首先按字母顺序打印其条目,然后按降序排列数据。所以最终结果将是:“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)
]

1 个答案:

答案 0 :(得分:3)

有两种方法可以做到这一点。两者都要求你将数组传递给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()
    
  3. 这两个实现都输出了你想要的结果:&#34; lukes 9&#34;,&#34; lukes 4&#34;,&#34; smiths 4&#34;