Print array in struct in alphabetical order and in descending order (swift3)

I would like my struct to print its entries by alphabetical order first then arrange the data from descending order way. So the final result should 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)
      ]

@timswift Thanks very much for your question! I would suggest something like this:

var dataSorted = data.sorted { ($0.company, $1.score) < ($1.company, $0.score) }

you can also do this:

let sortedData = data.sorted { ($0.company == $1.company) ? $0.score > $1.score : $0.company < $1.company}
print(sortedData)

I think either solution should do the trick :slight_smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.