基于布尔值的对象的Swift排序数组 [英] Swift sort array of objects based on boolean value

查看:183
本文介绍了基于布尔值的对象的Swift排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种基于布尔值对Swift数组进行排序的方法.

I'm looking for a way to sort a Swift array based on a Boolean value.

我已经使用对NSArray的强制转换了

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]

但是我正在寻找Swift变体,有什么想法吗?

But I'm looking for the Swift variant, any ideas?

更新 感谢Arkku,我设法使用以下代码解决了这个问题:

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

推荐答案

Swift的数组可以使用sort进行排序,或者使用sorted进行排序.这两个函数的单个参数都是一个闭合,它包含两个元素,并且如果第一个在第二个之前排序,则返回true.使用闭包参数的最短方法是将它们称为$0$1.

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

// In-place:
array.sort { $0.selected && !$1.selected }

// To a new array:
array.sorted { $0.selected && !$1.selected }

(针对Swift 3和Swift 4进行了更新,以前sortsortInPlacesortedsort.)

(edit: Updated for Swift 3 and 4, previously sort was sortInPlace and sorted was sort.)

这篇关于基于布尔值的对象的Swift排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆