Slightly weird SwiftData issue relating to background context inserts on a unrelated line of code

Hello. I had an issue that I was able to resolve, but I'd like to see if anyone might know why it happened in the first place. Essentially, I have a SwiftData model called Vehicle. This model has an array of Mileage, another SwiftData model. Vehicle has an init that accepts a Vehicle as a parameter and then matches it with that one.

init(from vehicle: Vehicle) {
        self.id = vehicle.id
        self.timestamp = vehicle.timestamp
        self.year = vehicle.year
        self.make = vehicle.make
        self.model = vehicle.model
        self.trim = vehicle.trim
        self.mileage = vehicle.mileage
        self.nickname = vehicle.nickname
    }

Previously, I had the line self.mileageHistory = vehicle.mileageHistory in this init. However, that line caused a duplicate Vehicle model to be created and inserted into the context. I could tell because I had a List that was displaying all of the created Vehicle models from a Query.

It all stems from a view that is being displayed in a sheet. This view accepts a vehicle parameter called copy.

.sheet(isPresented: $edit, content: { VehicleEditView(vehicle: vehicle, copy: Vehicle(from: vehicle)) })

In a way I can understand why it's happening because a new Vehicle model is being created. But I don't understand why it only happens when the mileageHistory variables are set equal to each other. I removed that line and it doesn't do it anymore. I had to workaround it by setting the mileageHistory elsewhere.

Does anyone know why this might be happening?

Could you explain a few points:

  • what is the purpose of copy parameter which recreates an instance of vehicle already passed as parameter ?
VehicleEditView(vehicle: vehicle, copy: Vehicle(from: vehicle))
  • show the complete declaration of Vehicle structure (mileageHistory is an array ? Is it a computed var ?).

Here is part of the Vehicle structure. I've left out some unrelated things like various functions.

@Model
final class Vehicle: Equatable, ContainsListItem {    
    var id: UUID
    // Other variables here...
    var mileageHistory: [Mileage] = []

Below is what the init look like when it has an issue.

init(from vehicle: Vehicle) {
        self.id = vehicle.id
        self.timestamp = vehicle.timestamp
        self.year = vehicle.year
        self.make = vehicle.make
        self.model = vehicle.model
        self.trim = vehicle.trim
        self.mileage = vehicle.mileage
        self.nickname = vehicle.nickname
        self.mileageHistory = vehicle.mileageHistory
    }

As a reminder, if you remove that last line in the init everything will work fine. If that line is there, a copy of Vehicle is being created and inserted into the context without me explicitly doing that.

Slightly weird SwiftData issue relating to background context inserts on a unrelated line of code
 
 
Q