gpt4 book ai didi

swift - 为什么我不能在 SwiftUI init 中为 @State var 赋值?

转载 作者:行者123 更新时间:2023-12-03 23:46:33 67 4
gpt4 key购买 nike

为什么这个赋值给 init 中的 @State var 不起作用?

class getOldValuesFromDb : ObservableObject {
@State var oldValue: Int = 0

init(){
let val = 999
self.oldValue = val
print("OldValue: \(self.oldValue) and Val: \(val)")
}
}
val 的值显示正确,但正如我将它分配给 oldValue ,它的值仍然为零。我的 print()看起来完全像这样: OldValue: 0 and Val: 999怎么可能?

最佳答案

我不确定 @State应该在 View 之外使用.

来自 Apple documentation :

SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.





You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing it. It is safe to mutate state properties from any thread.



您是否尝试使用 @Published反而 ?

关于swift - 为什么我不能在 SwiftUI init 中为 @State var 赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62393714/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com