Swift sort array of objects based on boolean value

ArraysSortingSwift

Arrays Problem Overview


I'm looking for a way to sort a Swift array based on a Boolean value.

I've got it working using a cast to NSArray:

var boolSort = NSSortDescriptor(key: "selected", ascending: false)
var array = NSArray(array: results)
return array.sortedArrayUsingDescriptors([boolSort]) as! [VDLProfile]

But I'm looking for the Swift variant, any ideas?

Update Thanks to Arkku, I've managed to fix this using the following code:

return results.sorted({ (leftProfile, rightProfile) -> Bool in
    return leftProfile.selected == true && rightProfile.selected != true
})

Arrays Solutions


Solution 1 - Arrays

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.)

Solution 2 - Arrays

New (for Swift 1.2)

return results.sort { $0.selected && !$1.selected }

Old (for Swift 1.0)

Assuming results is of type [VDLProfile] and VDLProfile has a Bool member selected:

return results.sorted { $0.selected < $1.selected }

See documentation for sorted

Solution 3 - Arrays

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAntoineView Question on Stackoverflow
Solution 1 - ArraysArkkuView Answer on Stackoverflow
Solution 2 - ArraysTeemu KurppaView Answer on Stackoverflow
Solution 3 - ArrayssaurabhView Answer on Stackoverflow