I am trying to sort my array by job hierarchy.
for example I have model:
struct Employee{
let name: String
let job: String
let phone: String
let mail: Sting
}
And then I have employees
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)
]
}
I would like to sort them to the list like this:
CEO Anna
Manager John
Kevin Senior Developer
Julia Junior Developer
Is there any easy way?
CodePudding user response:
Welcome to Stack Overflow! Please take the tour and see: How do I ask a good question? and How to create a Minimal, Reproducible Example. Your Employee
struct and your EmployeeViewModel.employees
didn't match, so I changed Employee
to conform. In order to make it sortable, Employee
has to conform to the Comparable
protocol. Since you wanted a set job order, the easiest way was to use an enum
to rank them. Also, Employee
should conform to the Identifiable
protocol to use them in a ForEach
for display purposes. You can cheat a bit, but eventually you will need to conform, so make it a habit from the beginning.
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"
}
}
}