I'm working through a tutorial on NSTableView with my own data. I've gotten to the point where I'm writing my sorting function, and this is what I've come up with:
var payment_list: [Payment]!
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else {
return
}
let key = sortDescriptor.key!
if sortDescriptor.ascending == true {
if key == "id" {
payment_list.sort { $0.id < $1.id }
} else if key == "msatoshi" {
payment_list.sort { $0.msatoshi < $1.msatoshi }
} else if key == "created_at" {
payment_list.sort { $0.created_at < $1.created_at }
} else if key == "status" {
payment_list.sort { $0.status < $1.status }
}
} else {
if key == "id" {
payment_list.sort(by: { $0.id > $1.id })
} else if key == "msatoshi" {
payment_list.sort { $0.msatoshi > $1.msatoshi }
} else if key == "created_at" {
payment_list.sort { $0.created_at > $1.created_at }
} else if key == "status" {
payment_list.sort { $0.status > $1.status }
}
}
tableView.reloadData()
}
It works fine, but I can't help but thinking that this is pretty verbose for something as common as sorting a multi-column list. The actual list in my app has several additional columns.
Are there any Swift tricks that I can use to make this code a bit more concise? Something like this would be more desirable:
if sortDescriptor.ascending == true {
payment_list.sort($0[key] < $1[key])
} else {
payment_list.sort($0[key] > $1[key])
}
Or maybe even something like:
payment_list = payment_list.sort(by: key, order: "ASC")
I get the impression that there are a lot of giant nested if...else if and/or switch...case blocks involved in Swift development. Is that an accurate assessment?
Update:
This is my Payment definition:
struct Payment: Codable, PaymentFactory {
let id: Int
let payment_hash: String
let destination: String
let msatoshi: Int
let timestamp: Int
let created_at: Int
let status: String
enum PaymentKeys: String, CodingKey {
case payments
}
static func fake() -> Payment {
// snipped for brevity
}
}
switchconstructs?switchvsif...elsedoesn't change the overall verbosity of the code. It would actually add eight lines of code using standard formatting.Paymentclass look like? What type are all your attributes?key, and it can have one of different values. I think control statements are the only way