Hello everyone,
I am new to the Swift and the SwiftUI. Trying to understand how sorting works on SwiftUI Table view.
The following code does what I intend to do, but I am not able to understand how does it actually work. Need help with the answers for the questions posted below the code.
import SwiftUI
struct Person: Identifiable {
let givenName: String
let familyName: String
let emailAddress: String
let id = UUID()
}
private var people = [
Person(givenName: "f1", familyName: "l1", emailAddress: "e1@example.com"),
Person(givenName: "f2", familyName: "l2", emailAddress: "e2@example.com"),
Person(givenName: "f3", familyName: "l3", emailAddress: "e3@example.com")
]
struct ContentView: View {
@State private var selected = Set<Person.ID>()
// Question 1
@State private var sortOrder = [KeyPathComparator(\Person.givenName)]
var body: some View {
Table(people, selection: $selected, sortOrder: $sortOrder) {
TableColumn("Given name", value: \.givenName)
TableColumn("Family name", value: \.familyName)
TableColumn("Email", value: \.emailAddress)
}
// Question 2
.onChange(of: sortOrder) { newOrder in
people.sort(using: newOrder)
}
}
}
Question 1 : I want to be able to sort by all the columns. How many KeyPathComparators should be in the sortOrder array?
Question 2: What is the value of newOrder? Is it same as the sortOrder? What does it contain?
Question 3: sortOrder contains the comparator for only givenName. How does the above code able to provide sort functionality for all the columns?