Ordina matrice in Swift
Per Swiftypersona di seguito è una tecnica molto pulita per raggiungere l'obiettivo sopra per globalmente. Consente di avere una classe personalizzata di esempio Usercon alcuni attributi.
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
}
Ora disponiamo di un array che dobbiamo ordinare in base createdDatea crescente o decrescente. Quindi, consente di aggiungere una funzione per il confronto delle date.
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
}
}
Ora consente di avere un extensiondi Arrayper User. In parole semplici, aggiungiamo alcuni metodi solo per quegli array che contengono solo Useroggetti.
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
}
}
Utilizzo per ordine crescente
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Utilizzo per ordine decrescente
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Utilizzo per lo stesso ordine
let sortedArray = someArray.sortUserByDate(.orderedSame)
Il metodo sopra descritto extensionsarà accessibile solo se Arraydi tipo
[User]||Array<User>