Question or problem in the Swift programming language:
Normally we can use didSet in swift to monitor the updates of a variable. But it didn’t work for a @Binding variable. For example, I have the following code:
@Binding var text { didSet { ...... } }
But the didSet is never been called.Any idea? Thanks.
How to solve the problem:
You shouldn’t need a didSet
observer on a @Binding
.
If you want a didSet
because you want to compute something else for display when text
changes, just compute it. For example, if you want to display the count of characters in text
:
struct ContentView: View { @Binding var text: String var count: Int { text.count } var body: some View { VStack { Text(text) Text(“count: \(count)”) } } }
If you want to observe text
because you want to make some other change to your data model, then observing the change from your View
is wrong. You should be observing the change from elsewhere in your model, or in a controller object, not from your View
. Remember that your View
is a value type, not a reference type. SwiftUI creates it when needed, and might store multiple copies of it, or no copies at all.