multidatepicker and saving multiple dates via swiftdata

Any help will be greatly appreciated.

Trying to build a calendar/planner app for public school teachers. Classes are held on multiple dates so there is a need for swiftdata to save multiple dates.

There are lots of tutorials demonstrating a multidatepicker but none of the tutorials or videos save the dates, via swiftdata.

My goal is to save multiple dates.

Step 1 is to initialize mockdata; this is done a class called ToDo. var dates:Set<DateComponents> = []

Step 2 is the view containing a multidatepicker and other essential code

Step 3 is to save multiple dates using swiftdata.

Lots of tutorials, code snippets and help using a single date.

But after almost 2 weeks of researching youtube tutorials, and google searches, I have not found an answer on how to save multiple dates via swiftdata.

Also, I don't know how how to initialize the array of <DateComponents> for the mockdata.

Here are some code snippets used but the initialization of the array of DateComponenets doesnt work. And saving multiple dates doesn't work either


@MainActor
@Model
class ToDo {
    var dates:Set<DateComponents> = []

     init(dates: Set<DateComponents> = []) {
        self.dates = dates
     }
}

//view
struct DetailView: View {
    @State var dates: Set<DateComponents> = []
   @Environment(\.modelContext) var modelContext
   @State var toDo: ToDo 
  @State private var dates: Set<DateComponents> = []
    
                MultiDatePicker("Dates", selection: $dates)
                    .frame(height: 100)

.onAppear() {  dates = toDo.dates }  

                       Button("Save") {
                         //move data from local variables to ToDo object
                         toDo.dates = dates
                        
                         //save data
                         modelContext.insert(toDo)
                        
                       }
                    }
}

#Preview {
        DetailView(toDo: ToDo())
            .modelContainer(for: ToDo.self, inMemory: true)
 
}
 

Use an Array instead of a Set in your model, use Date instead of DateComponents as the element type.

If using an array gives you warnings in the console similar to

CoreData: fault: Could not materialize Objective-C class named "Array" from declared attribute value type "Array<Date>" of attribute named ...

then you can wrap the Date property in a Codable structure and use that as a type

struct ToDoDate: Codable { 
    let date: Date
}

In model:

var dates: [ToDoDate] = []

Also, try to save the model context explicitly, as shown below:

modelContext.insert(toDo)
do {
    try modelContext.save()
} catch {
    print("Failed to save model context: \(error)")
}

SwiftData autosave doesn't quite work as you would expect in iOS 18 and friends, as discussed here.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

multidatepicker and saving multiple dates via swiftdata
 
 
Q