Swift 2.0按属性排序对象数组 [英] Swift 2.0 Sorting Array of Objects by Property
本文介绍了Swift 2.0按属性排序对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Swift 2.0中,您将如何通过属性对自定义对象数组进行排序?我知道在Swift 1.2中,这是使用sorted()和sort()完成的。但是,这些方法不再适用于Xcode 7 beta 4.谢谢!
In Swift 2.0, how would you go about sorting an array of custom objects by a property? I know in Swift 1.2, this was done using sorted() and sort(). However, these methods no longer work in Xcode 7 beta 4. Thanks!
例如:
class MyObject: NSObject {
var myDate : NSDate
}
...
let myObject1 : MyObject = MyObject() //same thing for myObject2, myObject3
var myArray : [MyObject] = [myObject1, myObject2, myObject3]
//now, I want to sort myArray by the myDate property of MyObject.
推荐答案
在Swift 2中:
-
您可以使用
sort
方法,使用比较
比较两个日期:
You can use
sort
method, usingcompare
to compare the two dates:
let sortedArray = myArray.sort { $0.myDate.compare($1.myDate) == .OrderedAscending } // use `sorted` in Swift 1.2
或者,如果你想要的话要对原始数组进行排序,您可以 sortInPlace
:
myArray.sortInPlace { $0.myDate.compare($1.myDate) == .OrderedAscending } // use `sort` in Swift 1.2
在Swift 3中:
-
返回数组的已排序再现,使用
已排序
,而非sort
let sortedArray = myArray.sorted { $0.myDate < $1.myDate }
要进行排序,它现在只是 sort
:
myArray.sort { $0.myDate < $1.myDate }
使用Swift 3的日期
类型,您可以使用<
运算符。
And with Swift 3's Date
type, you can use the <
operator.
这篇关于Swift 2.0按属性排序对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文