79082115

Date: 2024-10-12 23:17:02
Score: 0.5
Natty:
Report link

To really understand why you cannot change the value of tapCount, you'll need to do a bit of reading and gain a solid grasp on a number of Swift fundamentals, like value vs reference types, structs vs classes or this article on the same topic.

But, if you want to learn how it is done, rather than why it is done so, just know that in your code tapCount should be a @State and the increment function non-mutating. For some reading: Managing user interface state

Like this:

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()
}
Reasons:
  • Blacklisted phrase (1): this article
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Andrei G.