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)
]
There's 2 ways you can do this. Both would require you to pass your array to
sort
(Swift 2), nowsorted
(Swift 3).A very easy implementation:
You could also make
MyData
conform toComparable
. This keeps the comparison logic within the MyData type, and you can just run thesorted()
function to return a new array:These 2 implementations both output your desired result: "lukes 9", "lukes 4", "smiths 4"