I have a class defined like this:
class someClass {
var isCompleted = false
}
how to sort the list of the someClass? if want to move the completed items to the top of the list.
You can sort according to the boolean property by converting
the values to Int:
let arrayOfClasses = ... // array of classes
let sortedArrayOfClasses = sorted(arrayOfClasses) {
Int($0.isCompleted) > Int($1.isCompleted)
}
Or with "in-situ" sort:
var arrayOfClasses = ... // array of classes
sort(&arrayOfClasses) {
Int($0.isCompleted) > Int($1.isCompleted)
}
parameter closure for sort or sorted returns true iff the first parameter must be ordered before the second, otherwise false.
So you can:
let array = [ ... ]
let sortedArray = array.sorted { a, b in
a.isCompleted && !b.isCompleted
}
array.sorted { $0.isCompleted && !$1.isCompleted }
.filters or even a loop will likely be clearer to reaso about (and likely faster but who cares)