Swift sort array of objects based on boolean value

前端 未结 3 957
陌清茗
陌清茗 2020-12-09 07:30

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(         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 07:46

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

提交回复
热议问题