在 Xcode 的 Playground 我运行下面的代码:
import SwiftUI
struct Test {
@State var count: Int = 0 //to avoid "mutating" keyword, I use "@State" property wrapper
func countUp() {
self.count += 1
}
}
var test = Test()
test.countUp() // I want "count" property to be count up. but it did not
print(test.count) // print 0
Q)为什么test.count还是0??
最佳答案
这可能不是问题的意图,但我会解释为什么有问题的代码不起作用。(我相信这是同一件事 the comment。)
您正在 playground 中使用 SwiftUI
而不是 View
。
@State
符合 DynamicProperty
。
https://developer.apple.com/documentation/swiftui/state https://developer.apple.com/documentation/swiftui/dynamicproperty
文档说:
You should only access a state property from inside the view’s body, or from methods called by it.
An interface for a stored variable that updates an external property of a view. and The view gives values to these properties prior to recomputing the view’s body.
建议将它与 View
和 view's body
一起使用。
如上所述,您的代码不使用View
或view's body
。
因为@State
只能在struct
中使用,如果你想做类似的事情,你可以使用class
并使用@Published
如下图(简单使用Combine
,不是SwiftUI
):
import Combine
class Test {
@Published var count: Int = 0
func countUp() {
self.count += 1
}
}
var test = Test()
test.countUp()
print(test.count) // 1
但是,您的代码没有人订阅更改,因此这只是一个实验代码。
关于swift - 可以通过其结构的方法更改@State 属性的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67848526/