Thanks for all the replies. They have been very helpful, I come from a IBM C, COBOL, Assembler, REXX etc. coding background so the transition to swift had been daunting.
At this point I have added the coding you all supplied to my project but I am not sure how to connected it or use it within the framework of my project.
Let me supply some more details.
- I am using SQLite for a backend
- I am using a structure called Customers to reference the rows in the SQLite table
- I am using a tableview in Interface Builder to display customer data.
- I want to sort on a column that contains customer name (First Name and Last Name)
So, in ViewController code I have the following:
func setSortDescriptor() {
let descriptorID = NSSortDescriptor(key: "custnumber", ascending: true)
tableView.tableColumns[0].sortDescriptorPrototype = descriptorID
let descriptorName = NSSortDescriptor(key: "custname", ascending: true)
tableView.tableColumns[1].sortDescriptorPrototype = descriptorName
let descriptorDate = NSSortDescriptor(key: "custdate", ascending: true)
tableView.tableColumns[8].sortDescriptorPrototype = descriptorDate
}
and in the DataSource of my View controller I have the following:
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else { return }
let custColumn = sortDescriptor.key!
custviewModel.sortCustomers(custColumn: custColumn, ascending: sortDescriptor.ascending)
tableView.reloadData()
}
and in custviewModel I have the following:
class CustViewModel: NSObject {
// MARK: - Properties
var customers = [Customers]()
// MARK: - Init
override init() {
super.init()
customers = getAllCustomers()
}
// MARK: - Private Methods
// MARK: - Public Methods
func sortCustomers(custColumn: String, ascending: Bool) {
switch custColumn {
case "custname":
customers.sort { (p1, p2) -> Bool in
guard let id1 = p1.id, let id2 = p2.id else { return true }
if ascending {
return id1 < id2
} else {
return id2 < id1
}
}
As you can see the sort for customer name currently sorts on the entire Name Column and the customer variable contains my SQLIte rows that I now sort on and reload the tableview.
So how do use the code you all have supplied? I think it needs to be in the sortCustomers function?
Thanks