在 Swift 中排序数组
For Swifty
Person below 是一种非常干净的技术,可以在全球范围内实现上述目标。让我们有一个示例自定义类,User
其中包含一些属性。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
}
现在我们有一个数组,我们需要根据createdDate
升序和/或降序对其进行排序。因此,让我们添加一个日期比较功能。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
func checkForOrder(_ otherUser: User, _ order: ComparisonResult) -> Bool {
if let myCreatedDate = self.createdDate, let othersCreatedDate = otherUser.createdDate {
//This line will compare both date with the order that has been passed.
return myCreatedDate.compare(othersCreatedDate) == order
}
return false
}
}
现在让我们有extension
一个Array
for User
。简而言之,让我们只为那些只有User
对象的数组添加一些方法。
extension Array where Element: User {
//This method only takes an order type. i.e ComparisonResult.orderedAscending
func sortUserByDate(_ order: ComparisonResult) -> [User] {
let sortedArray = self.sorted { (user1, user2) -> Bool in
return user1.checkForOrder(user2, order)
}
return sortedArray
}
}
升序的用法
let sortedArray = someArray.sortUserByDate(.orderedAscending)
降序的用法
let sortedArray = someArray.sortUserByDate(.orderedAscending)
相同订单的用法
let sortedArray = someArray.sortUserByDate(.orderedSame)
上面的方法extension
只有在Array
类型为
[User]
||时才能访问。Array<User>