Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }) 
like image 657
Antoine Avatar asked Feb 28 '15 11:02

Antoine


People also ask

How do you sort an array of objects in Swift?

In Swift, we can also sort arrays in ascending and descending order. To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order.

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.

Does sort work with objects?

The objects can contain key-value pair and have properties and values. We can sort the array of objects using the sort() method in javascript and then provide a comparison function that will ultimately determine the order of the objects.


2 Answers

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

like image 179
Arkku Avatar answered Sep 19 '22 17:09

Arkku


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

like image 35
Teemu Kurppa Avatar answered Sep 19 '22 17:09

Teemu Kurppa