I am creating an application in Swift, and I am creating a section with a calendar where you will be able to see the list of users with a numeric data entered by them. These data are collected in a structure as follows:
struct User: Identifiable {
var id: String = UUID().uuidString
var name: String
var surname: String
var timetables: [String]
var toCheck: [String] {
return [name, surname]
}
}
User information is displayed like this:
ForEach(administratorManager.users) { user in
HStack {
VStack(alignment: .leading) {
Text(user.name).font(.subheadline)
Text(user.surname).font(.subheadline)
Text(user.orari[day]).font(.subheadline)
}
}
Spacer()
}
And they are displayed on the screen like this: Photo of the list displayed on the screen
The data is sorted according to their position in the database:
I'd like to sort the list by the number entered under the user's first and last name (the smallest above and so on). Anyone know how to fix?
CodePudding user response:
Assuming administratorManager.users
is a Swift.Array
(or other sortable in-memory collection), you can sort it however you want. This is one possible way you might sort on the surname and name fields:
var body: some View {
ForEach(administratorManager.users.sorted(using: [
KeyPathComparator(\.surname, order: .forward),
KeyPathComparator(\.name, order: .forward),
])) { user in
Text(user.name)
}
}
If you want to sort on the initial element of the associated timetables
array, you can traverse a property with the KeyPathComparator
:
KeyPathComparator(\.timetables.first, order: .forward)
And if the value needs to be calculated, you can add it as a calculated property:
extension User {
var minTimetable: String? {
timetables.min()
}
}
and then reference that property from the comparator:
KeyPathComparator(\.minTimetable, order: .forward)