Hi,
it seems that a @State
variable in a View
will not update (initialize to the new value) on subsequent calls to the View
s .init
method.
In the example below (tested on macOS) the Text("internal: \(_internalNumber)")
still shows 41, even after 1s is over and number was set to 42 (in the .task
).
TestView.init
runs as expected and _internalNumber
shows the correct value there, but in the body
method (on the redraw) _internalNumber
still has the old value.
This is not how it should be, right?
import SwiftUI
struct ContentView: View {
@State private var number = 41
var body: some View {
VStack {
TestView(number: number)
.fixedSize()
}
.task {
try! await Task.sleep(nanoseconds: 1_000_000_000)
await MainActor.run {
print("adjusting")
number = 42
}
}
}
}
////////////////////////
// MARK: - TestView -
public struct TestView: View {
public init(number: Int) {
self.number = number
__internalNumber = .init(initialValue: number)
print("Init number: \(self.number)")
print("Init _internalNumber: \(_internalNumber)")
}
var number: Int
@State private var _internalNumber: Int
public var body: some View {
VStack(alignment: .leading) {
Text("number: \(number)")
Text("internal: \(_internalNumber)")
}
.debugAction {
Self._printChanges()
print("number: \(number)")
print("_internalNumber: \(_internalNumber)")
}
}
}
// MARK: - debugAction
extension View {
func debugAction(_ closure: () -> Void) -> Self {
closure()
return self
}
}