I use view-based NSTableView
in my Cocoa app which is written in Swift, and want to implement a sort functionality on two table columns. However, in Objective-C, you can implement it by first setting the "Sort Key" in Attribute Inspector, and then implement the data source delegate method named tableView: sortDescriptorsDidChange:
.
However, this method takes sortDescriptor
as a parameter and lets developers use it within the method, like so:
- (void) tableView:( NSTableView *) tableView sortDescriptorsDidChange:( NSArray *) oldDescriptors {
[self.songs sortUsingDescriptors:tableView.sortDescriptors];
[tableView reloadData];
}
However, in Swift Array, there are no such method as sortUsingDescriptors
. So I first tried to convert Array
to NSMutableArray
in order to use the NSMutableArray
's method, but since my Swift Array is defined as AnyObject[]
, it cannot be casted to NSMutableArray
.
So how should I implement the sort functionality to the table view in Swift? I know Swift Array can use sort
function to sort the object by comparing the two arguments and returning bool values, but is it possible to use sortDescriptors
to sort the table? Or should I just ignore the sortDescriptors
argument and instead write my own sort logic manually? (but then I don't know how to tell what column is clicked without the sortDescriptors
value).