我是学习 swift 和 swiftui 的新手。我写的代码有错误
不能对不可变值使用变异成员:“self”是不可变的
这是代码:
import SwiftUI
struct ContentView: View {
var tapCount = 0
var body: some View {
Button("Tap Count: \(tapCount)") {
self.incrementCount()
}
}
mutating func incrementCount() {
self.tapCount += 1
}
}
我不明白为什么我无法更改 tapCount
的值要真正理解为什么无法更改
tapCount
的值,您需要进行一些阅读并扎实掌握一些 Swift 基础知识,例如值与引用类型、结构与类或这篇文章关于同一主题。
但是,如果您想了解它是如何完成的,而不是为什么这样做,只需知道在代码中 tapCount 应该是
@State
并且增量函数不可变。一些阅读:管理用户界面状态
像这样:
struct IncrementButton: View {
@State private var tapCount = 0
var body: some View {
Button("Tap Count: \(tapCount)") {
self.incrementCount()
}
}
private func incrementCount() {
self.tapCount += 1
}
}
#Preview {
IncrementButton()
}