Sort array of objects by two properties

Conform to Comparable! 😺

extension Sortable: Comparable {
  static func < (sortable0: Sortable, sortable1: Sortable) -> Bool {
    sortable0.isPriority == sortable1.isPriority
    ? sortable0.ordering < sortable1.ordering
    : sortable0.isPriority
  }
}

Which will allow for:

sortableArray.sorted()

Here is a simple statement to do this sorting:

var sorted = array.sort { $0.isPriority == $1.isPriority ? $0.ordering < $1.ordering : $0.isPriority && !$1.isPriority }

Yes there is a very simple way using the Array.sort()

Code:

var sorted = array.sorted({ (s1, s2) -> Bool in
    if s1.isPriority && !s2.isPriority {
        return true //this will return true: s1 is priority, s2 is not
    }
    if !s1.isPriority && s2.isPriority {
        return false //this will return false: s2 is priority, s1 is not
    }
    if s1.isPriority == s2.isPriority {
        return s1.ordering < s2.ordering //if both save the same priority, then return depending on the ordering value
    }
    return false
})

The sorted array:

true - 10
true - 10
true - 12
true - 12
true - 19
true - 29
false - 16
false - 17
false - 17
false - 17
false - 18

Another a bit shorter solution:

let sorted = array.sorted { t1, t2 in 
   if t1.isPriority == t2.isPriority {
      return t1.ordering < t2.ordering 
   }
   return t1.isPriority && !t2.isPriority 
}

Tags:

Sorting

Swift