在Swift中排序数组
对于Swifty
以下人员而言,这是一种非常干净的技术,可以在全球范围内实现上述目标。让我们来看一个示例自定义类,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
了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]
||的上述方法in 才可访问Array<User>