Antoine Antoine - 1 month ago 8
Swift Question

Swift sort array of objects based on boolean value

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

Answer

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 iff 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):

array.sort { $0.selected && !$1.selected }

(edit: Updated for Swift 3, previously these were sortInPlace and sort.)