gpt4 book ai didi

ios - NSSortDescriptor 比 swift 高阶函数有什么优势?

转载 作者:行者123 更新时间:2023-11-28 10:52:09 28 4
gpt4 key购买 nike

下面是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com