(Using XCode 13.4 / iOS 15)
I have a @Published array that is presented to the user in a List with the ability to make changes to the items. The source of the array is from a file that is updated once the user makes changes to the items.
The sample code below shows how I'm currently doing that.
My question is: I want the List that is presented to the user to be sorted. How can I do that without changing the underlying @Published array, while still enabling the user to make changes to the items?
struct Contact: Identifiable {
let id = UUID()
var firstName: String
var lastName: String
var dateOfBirth: Date
}
class ViewModel: ObservableObject {
@Published var contacts: [Contact]
static let shared = ViewModel()
private init() {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyyy"
let sampleData = [
Contact(firstName: "James", lastName: "Smith", dateOfBirth: formatter.date(from: "2-Jan-1965")!),
Contact(firstName: "John", lastName: "Johnson", dateOfBirth: formatter.date(from: "7-Feb-1982")!),
Contact(firstName: "David", lastName: "Brown", dateOfBirth: formatter.date(from: "22-Mar-1971")!),
Contact(firstName: "Michael", lastName: "Jones", dateOfBirth: formatter.date(from: "15-Aug-2002")!),
Contact(firstName: "Robert", lastName: "Davis", dateOfBirth: formatter.date(from: "11-Nov-2010")!),
]
contacts = sampleData
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel.shared
var body: some View {
List {
ForEach($viewModel.contacts) {$contact in
HStack {
Text("\(contact.firstName) \(contact.lastName)")
DatePicker("", selection: $contact.dateOfBirth, displayedComponents: [.date])
}
}
}
}
}