下面是使用NSSortDescriptor
的示例,其结果与sortedByFirstNameSwifty
相同,那么Swift中需要什么NSSortDescriptor
?
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]
最佳答案
NSSortDescriptor的优点是,您可以使用它们的数组进行排序,如果根据第一个描述符两个对象相等,则可以返回到第二个描述符进行排序。
例如,假设您按修改日期对多个文件进行排序。如果两个文件恰好具有完全相同的修改日期,则可能需要按名称对这两个文件进行排序。所以您将使用一个排序描述符数组,第一个按日期排序,第二个按文件名排序。
关于ios - NSSortDescriptor相对于swift高阶函数有什么优势?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45675457/