I noticed updating a @Transient
attribute's value does not refresh SwiftUI views when using a SwiftData model with @Query
or @Bindable
.
Here is a sample code (clicking the button changes the Transient attribute):
import SwiftUI
import SwiftData
// SwiftUI App struct declaration
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: MyModel.self)
}
}
// My SwiftData test model
@Model
class MyModel {
var myFirstArray: [Int]
@Transient var mySecondElement: Bool = false
init(myFirstArray: [Int] = [Int](), mySecondElement: Bool = false) {
self.myFirstArray = myFirstArray
self.mySecondElement = mySecondElement
}
}
// The SwiftUI View
struct ContentView: View {
@Query var myModels: [MyModel]
@Environment(\.modelContext) var modelContext
var body: some View {
VStack {
if myModels.count != 0 {
Text("Model:")
// I expected this to update when the button is clicked
Text("mySecondElement's value: \(myModels[0].mySecondElement ? "True" : "False" )")
Button {
// button that changes the transient attribute
myModels[0].mySecondElement.toggle()
print(myModels[0].mySecondElement) // this prints the actual value
} label: {
Text("Add mySecondElement data")
}
}
}
.onAppear {
try? modelContext.delete(model: MyModel.self)
if myModels.count == 0 {
let model = MyModel(myFirstArray: [0, 1, 3])
modelContext.insert(model)
}
}
}
}
I expected ContentView()
to be refreshed when I clicked on the button. However, this seems to not be the case - it seems that attributes marked with @Transient
don't publish updates to Views.
Is this expected behaviour? Should I file a bug / feedback for this?