swift - 可以通过其结构的方法更改@State 属性的值吗?

标签 swift swiftui

在 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.

建议将它与 Viewview's body 一起使用。

如上所述,您的代码不使用Viewview'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/

相关文章:

swift - Finder 同步扩展无法从桌面读取/写入文件

ios - 点击列表项时如何显示 View ?

swift - 为什么我在切换屏幕时会丢失我的 SwiftUI View

swiftui - 是否有edgesIgnoringSafeArea 无值?

swiftui - 刷新 NavigationView 环境对象

ios - Int 参数传入方法时变为 0

swift - 创建主键的最佳方式 - Swift

iOS Swift - 使用 UISegmentedControl 更改 UIPageViewController 页面

ios - 在 swiftui 中关闭 View

swift - UICollectionViewCell 不显示从 UIImagePickerController 选取的图像