问题
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:
There's 2 ways you can do this. Both would require you to pass your array to sort (Swift 2), now sorted (Swift 3).
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) })You could also make
MyDataconform toComparable. This keeps the comparison logic within the MyData type, and you can just run thesorted()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"
来源:https://stackoverflow.com/questions/46019062/print-array-in-struct-in-alphabetical-order-and-in-descending-order