按字母顺序和降序打印结构中的数组 [英] print array in struct in alphabetical order and in descending order

查看:27
本文介绍了按字母顺序和降序打印结构中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like my struct to print its entries in alphabetical order first, then arrange the data in descending order. So the final result would be: "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)
]

推荐答案

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

There's 2 ways you can do this. Both would require you to pass your array to sort (Swift 2), now sorted (Swift 3).

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

  1. A very easy implementation:

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) })

  • 您还可以使 MyData 符合 Comparable.这将比较逻辑保留在 MyData 类型中,您只需运行 sorted() 函数即可返回一个新数组:

  • You could also make MyData conform to Comparable. This keeps the comparison logic within the MyData type, and you can just run the sorted() function to return a new array:

    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()
    

  • 这两个实现都输出你想要的结果:lukes 9"、lukes 4"、smiths 4"

    These 2 implementations both output your desired result: "lukes 9", "lukes 4", "smiths 4"

    这篇关于按字母顺序和降序打印结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆