print array in struct in alphabetical order and in

2019-08-22 00:44发布

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

1条回答
Ridiculous、
2楼-- · 2019-08-22 01:22

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. 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) })
    
  2. 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()
    

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

查看更多
登录 后发表回答