Swift sort array of objects based on boolean value
Swift's arrays can be sorted in place with sort
or to a new array with sorted
. The single parameter of either function is a closure taking two elements and returning true
if the first is ordered before the second. The shortest way to use the closure's parameters is by referring to them as $0
and $1
.
For example (to sort the true booleans first):
// In-place:array.sort { $0.selected && !$1.selected }// To a new array:array.sorted { $0.selected && !$1.selected }
(edit: Updated for Swift 3, 4 and 5, previously sort
was sortInPlace
and sorted
was sort
.)
Swift’s standard library provides a function called sorted, which sorts an array of values of a known type, based on the output of a sorting closure that you provide
reversed = sorted(array) { $0 > $1 }
reversed
will be a new array which will be sorted according to the condition given in the closure.