Is this a bug or a feature?

I recently encountered a "potential bug" with SwiftData. I save my model with modelContent.insert and after that I get following error when trying to delete it with modelContent.delete: Could not cast value of type 'Swift.Optional<Any>' (0x1f5b871f8) to 'Foundation.UUID' This I mentioning the let id: UUID field marked with @Attribute(.unique).

This build doesn't crash running in an iOS Sim but if it's running thought TestFlight on my iPhone it just crashes.

If I try to delete elements that aren't just created, I don't get this error.

Replies

You didn't save your model with insert. You only inserted the data into the context. You need to either save the context or wait for an auto save.

I am experiencing the exact same problem with the current iOS/Xcode version. The issue occurs intermittently but completely breaks the database. It appears that the data is not always saved correctly, and attempting to load it subsequently leads to an exception. In my network measurement app, I attempt to store the results using SwiftData. I have tried disabling autosave and saving the context manually, but the problem persists. Additionally, I tried removing the @Attribute(.unique) from my UUID field, but this does not seem to resolve the issue.

This is my model:

@Model
internal class StorageModel {
    var uuid: UUID
    var date: Date
    var result: ResultModel
    
    required init(uuid: UUID = UUID(), date: Date = Date(), result: ResultModel = .init()) {
        self.uuid = uuid
        self.date = date
        self.result = result
    }
}

I'm experiencing the same issue as well. This wasn't there with the earlier version because I've tested this thoroughly. It now happens to me when I'm trying to delete a newly created object. The app just crashes and I'm receiving the same error message.

I have found a Solution that worked for me and I was able to reproduce the error. It seems that SwiftData don't likes having directly optional values. I attached an example for better understanding. If I have no optionals directly (inside an array it seems to work) the problem is gone for me.

@Model
internal class StorageModel {
    var uuid: UUID
    var date: Date
    var result: ResultModel
    
    required init(uuid: UUID = UUID(), date: Date = Date(), result: ResultModel = .init()) {
        self.uuid = uuid
        self.date = date
        self.result = result
    }
}

internal struct ResultModel: Codable {
    internal var uuid = UUID()
    internal var locations: [LocationModel] = [] // This is okay
    internal var location = LocationModel? // This causes the crash for me
    internal var workingLocation = LocationModel(latitude: .zero, longitude: .zero) // This is also okay
}

internal struct LocationModel: Codable {
    internal var latitude: Double?
    internal var longitude: Double?
    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }
}