I am trying to sort an array of Custom Structs by different property values easily.
struct Customer: Comparable, Equatable {
var name: String
var isActive: Bool
var outstandingAmount: Int
var customerGroup: String
}
var customerlist: [Customer] // This is downloaded from our backend.
I want to be able to sort the customerlist array in the UI by all the field values when the user selects the various icons.
I have tried a few methods to sort it using a switch statement - however I am told that the correct way to do this is using Sort Descriptors( which appear to be Objective-C based and mean I need to convert my array to an NSArray. ) I keep getting errors when I try this approach with native Swift structs.
What is the best way to allow the user to sort the above array using Swift?
Eg: below seems very verbose!
func sortCustomers(sortField:ColumnOrder, targetArray:[Customer]) -> [Customer] { //Column Order is the enum where I have specified the different possible sort orders
var result = [Customer]()
switch sortField {
case .name:
result = targetArray.sorted(by: { (cust0: Customer, cust1: Customer) -> Bool in
return cust0.name > cust1.name
})
case .isActive:
result = targetArray.sorted(by: { (cust0: Customer, cust1: Customer) -> Bool in
return cust0.isActive > cust1.isActive
})
case .outstandingAmount:
result = targetArray.sorted(by: { (cust0: Customer, cust1: Customer) -> Bool in
return cust0.outstandingAmount > cust1.outstandingAmount
})
case .customerGroup:
result = targetArray.sorted(by: { (cust0: Customer, cust1: Customer) -> Bool in
return cust0.customerGroup > cust1.customerGroup
})
}
return result
}
targetArray.sorted { $0.name > $0.name })