迅速.使用字符串变量的属性名对结构数组进行排序



我有一个简单的代码:

struct User {
let id: Int
let name: String
}
var users: [User] = [User(id:1, name:"Alpha"), User(id:2, name:"Beta"), User(id:3, name:"Gamma")]
print(users)
users.sort { $0.name > $1.name }
print(users)

基于变量改变排序字段的最好方法是什么?我的意思是,我想要一些变量,比如"sortBy"其中包含排序字段的值("id";"name";等等,结构可能包含几十个字段)。在Swift中我找不到正确的方法。

伪代码:

var sortBy = "name"
users.sort { $0.{sortBy} > $1.{sortBy} }

使用关键路径和方法

users.sort(by: .name)
users.sort(by: .id)
extension Array where Element == User {
mutating func sort<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable
) rethrows {
self = try sorted(by: comparable, >)
}
}
public extension Sequence {
/// Sorted by a common `Comparable` value, and sorting closure.
func sorted<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable,
_ areInIncreasingOrder: (Comparable, Comparable) throws -> Bool
) rethrows -> [Element] {
try sorted {
try areInIncreasingOrder(comparable($0), comparable($1))
}
}
}

最新更新