SwiftData Model didset

Hi, I'm trying out new SwiftData in a small Xcode project. It seems that the property observers didSet and willSet don't work anymore for swift data anymore. In code like this, the didSet does nothing and seems to never be called.


@Model public final class importConfig: Identifiable, ObservableObject{
    @Attribute(.unique) public var id: UUID

    /// Name of the configuration
    var configName: String

    /// Numbers App document to open
    var numbersFilePath: URL?

    /// Indicate wether current <numbersFilePath> Numbers App document has been loaded and analyzed
    var isLoaded: Bool = false

    /// Current selected sheet
    var selectedSheetID: UUID? {
        didSet {
            selectedSheetID = nil
            print("test")
        }
    }
}

Am I doing something wrong or is it the expected behavior ? If it is the expected behavior, how can I add "business" rules when setting/unsetting value to model properties ? I tried to add rules directly with .onchange() in my views, but this way I have to repeat the same rules/code. Is there any alternative to do so ?

Thank you

I also like to validate inside the model. But I'm not sure what is the best way to do this.

Is this good practice?

@Model public final class importConfig: Identifiable, ObservableObject{
    ...
    private var _selectedSheetID: UUID?

    var selectedSheetID: UUID? {
        get { return __selectedSheetID }
        set {
            // validation
            selectedSheetID = newValue
        }
    }
}

It's somewhat I finally done in my code. But, for this to work, it's mandatory to use @Transient macro to tell Xcode the property is not persistent. This approach involves to "double" some properties, as you've done in your example. So, for your solution to work just add @Transient for the _selectedSheetID property and it'll work. Like this :

@Model public final class importConfig: Identifiable, ObservableObject{
    ...
    private var _selectedSheetID: UUID?

    @Transient var selectedSheetID: UUID? {
        get { return __selectedSheetID }
        set {
            // validation
            selectedSheetID = newValue
        }
    }
}

It allows to remove lots of .onChange logic in the view (and that logic should NOT be in the view), and better the "business logic" is in the model and wherever the model is used, you ensure the same behavior.

SwiftData Model didset
 
 
Q