0

Currently I sort and array by doing the following

self.list = self.list.sorted(by: { $0.priority < $1.priority })

But I also was the array to be sorted by a second property called number

Class Item {
   var number: Int = 0
   var priority: Int = 0
}

The array should be displayed in order like so,

priority = 1, number = 3
priority = 1, number = 4
priority = 1, number = 5
priority = 1, number = 7
priority = 2, number = 1
priority = 2, number = 5

However as of right now is shown like so

priority = 1, number = 7
priority = 1, number = 5
priority = 1, number = 3
priority = 1, number = 4
priority = 2, number = 5
priority = 2, number = 1

I thought maybe something like so would work,

self.list = self.list.sorted(by: { $0.priority < $1.priority && $0.number < $1.number })

But it does not sort at all. Does anybody know how I ca sort the array ?

RileyDev
  • 2,950
  • 3
  • 26
  • 61
  • `sort(by: { if $0.priority == $1.priority { return $0.number < $1.number } else return $0.priority < $1.priority })`? With words: Between two elements, to we check priority. If it's the same, we compare number. If not, we compare priority. – Larme Oct 25 '18 at 15:11
  • 1
    Since you only have two properties, you can simplify that even more to a ternary operator: `self.list.sorted(by: {$0.priority == $1.priority ? $0.number < $1.number : $0.priority < $1.priority})` – Dávid Pásztor Oct 25 '18 at 15:14

0 Answers0