Reputation: 14349
Below is example use of NSSortDescriptor
which gives same result as sortedByFirstNameSwifty
then whats need of NSSortDescriptor
in Swift ?
class Person: NSObject {
let firstName: String
let lastName: String
let age: Int
init(firstName: String, lastName: String, age: Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
override var description: String {
return "\(firstName) \(lastName)"
}
}
let a = Person(firstName: "a", lastName: "b", age: 24)
let b = Person(firstName: "c", lastName: "d", age: 27)
let c = Person(firstName: "e", lastName: "f", age: 33)
let d = Person(firstName: "g", lastName: "h", age: 31)
let peopleObject = [d, b, a, c]
//SWIFTY
let sortedByFirstNameSwifty = peopleObject.sorted(by: { $0.firstName < $1.firstName })
print(sortedByFirstNameSwifty)//prints[a b, c d, e f, g h]
//Objective c way
let firstNameSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
let sortedByFirstName = (peopleObject as NSArray).sortedArray(using: [firstNameSortDescriptor])
print(sortedByFirstName)//prints [a b, c d, e f, g h]
Upvotes: 0
Views: 232
Reputation: 17060
The advantage of NSSortDescriptor is that you can sort using an array of them, and if two objects turn out to be equal according to the first descriptor, you can then fall back on the second descriptor to sort them.
For example, say you were sorting a number of files by modification date. In the event that two files happen to have exactly the same modification date, you might want to sort those two files by name instead. So you would use an array of sort descriptors, the first of which sorts by date and the second of which sorts by filename.
Upvotes: 5