If all the properties that are used for sorting have the same type, you could use the built-in key-value access. Consider the following class A with two properties a and b both of which are strings.
class A: NSObject, Printable {
var a: String
var b: String
init(a: String, b: String) {
self.a = a
self.b = b
}
override var description: String {
return "{ a: \(self.a), b: \(self.b) }"
}
}
Let's say your table contents are build from instances of this class.
var tableContents = [A(a: "1", b: "2"), A(a: "2", b: "1")]
To sort this array based on the values of either a or b you could use the following.
tableContents.sort {
let key = "a"
let oneValue = $0.valueForKey(key) as! String
let otherValue = $1.valueForKey(key) as! String
return oneValue.localizedCaseInsensitiveCompare(otherValue) == NSComparisonResult.OrderedAscending
}
println(tableContents) // [{ a: 1, b: 2 }, { a: 2, b: 1 }]
tableContents.sort {
let key = "b"
let oneValue = $0.valueForKey(key) as! String
let otherValue = $1.valueForKey(key) as! String
return oneValue.localizedCaseInsensitiveCompare(otherValue) == NSComparisonResult.OrderedAscending
}
println(tableContents) // [{ a: 2, b: 1 }, { a: 1, b: 2 }]
The only difference in the comparison block is the usage of either let key = "a" or let key = "b".