为什么我无法更改 SwiftUI Struct 中的 var 属性?

问题描述 投票:0回答:1

我是学习 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

的值
swift swiftui
1个回答
0
投票

要真正理解为什么无法更改

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()
}
© www.soinside.com 2019 - 2024. All rights reserved.