Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

sorting - 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
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...