SwiftUI 按作业层次排序列表
Posted
技术标签:
【中文标题】SwiftUI 按作业层次排序列表【英文标题】:SwiftUI sort list by job hierarchy 【发布时间】:2021-12-31 17:44:06 【问题描述】:我正在尝试按作业层次结构对数组进行排序。
例如我有模型:
struct Employee
let name: String
let job: String
let phone: String
let mail: Sting
然后我有员工
class EmployeeViewModel: ObservableObject
@Published var employees: [Employee] = [
Employee(name: "John", job: "Manager", age: 32),
Employee(name: "Anna", job: "CEO", age: 40),
Employee(name: "Julia", job: "Junior Developer", age: 25),
Employee(name: "Kevin", job: "Senior Developer", age: 29)
]
我想将它们排序到这样的列表中:
CEO Anna
Manager John
Kevin Senior Developer
Julia Junior Developer
有什么简单的方法吗?
【问题讨论】:
【参考方案1】:您的 Employee
结构和您的 EmployeeViewModel.employees
不匹配,所以我更改了 Employee
以符合要求。为了使其可排序,Employee
必须符合Comparable
协议。由于您想要一个固定的工作订单,最简单的方法是使用enum
对它们进行排名。此外,Employee
应符合Identifiable
协议,以便在ForEach
中使用它们以用于显示目的。你可以作弊,但最终你需要顺从,所以从一开始就养成习惯。
struct SortByJob: View
@StateObject var employeeVM = EmployeeViewModel()
var body: some View
List
ForEach(employeeVM.employees.sorted()) employee in
HStack(spacing: 5)
Text(employee.job.description)
Text(employee.name)
struct Employee: Identifiable, Comparable
let id = UUID()
let name: String
let job: Job
let age: Int
static func < (lhs: Employee, rhs: Employee) -> Bool
lhs.job.rawValue < rhs.job.rawValue
enum Job: Int
case ceo = 1
case manager = 2
case seniorDeveloper = 3
case juniorDeveloper = 4
// This allows you to return a String from the enum for display purposes.
var description: String
switch self
case .ceo:
return "CEO"
case .manager:
return "Manager"
case .seniorDeveloper:
return "Senior Developer"
case .juniorDeveloper:
return "Junior Developer"
【讨论】:
以上是关于SwiftUI 按作业层次排序列表的主要内容,如果未能解决你的问题,请参考以下文章