I was looking to the example code that point from What's new in SwiftData session and noticed something that I cannot understand about Swift concurrency. from this snippet:
static func createSampleData(into modelContext: ModelContext) {
Task { @MainActor in
let sampleDataTrips: [Trip] = Trip.previewTrips
let sampleDataLA: [LivingAccommodation] = LivingAccommodation.preview
let sampleDataBLT: [BucketListItem] = BucketListItem.previewBLTs
let sampleData: [any PersistentModel] = sampleDataTrips + sampleDataLA + sampleDataBLT
sampleData.forEach {
modelContext.insert($0)
}
if let firstTrip = sampleDataTrips.first,
let firstLivingAccommodation = sampleDataLA.first,
let firstBucketListItem = sampleDataBLT.first {
firstTrip.livingAccommodation = firstLivingAccommodation
firstTrip.bucketList.append(firstBucketListItem)
}
if let lastTrip = sampleDataTrips.last,
let lastBucketListItem = sampleDataBLT.last {
lastTrip.bucketList.append(lastBucketListItem)
}
try? modelContext.save()
}
}
From the code snippet, I cannot see any task that needs to be marked with await, and it is also marked as @MainActor.
My question is: why do we need to put Task here? It seems like all the code will run on the main thread anyway. I am just afraid that I might be missing some concept of Swift concurrency or SwiftData here.
Thank you