82

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
})
1
  • 1
    re. update in the question, comparing booleans with true is unnecessary clutter, and it would be better Swift style to omit the () around the closure (as is permitted when the closure is the last argument). Commented Nov 21, 2015 at 16:25

3 Answers 3

186

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, using your answer I've managed to fix this in Swift. I've updated my question with the answer.
Please note that in Swift 3.0 .sort is used
5

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

1 Comment

This gave me an error: Cannot invoke 'sorted' with an argument list of type.
-1

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.

1 Comment

This doesn't answer the question - OP needs to sort by boolean values which cannot be compared using > or <. (also the first sentence is copied word for word from the Swift book)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.