SwiftUI - how to increment @state var integer by one

struct ContentView: View {

@State private var num = 0

var body: some View {

Text("Hello, World!")

self.num += 1


}

}


How can I increment num? i have tried all suggestions i have received, but no luck ...

Can do this, which works with several buttons:


import SwiftUI

class UserSettings: ObservableObject {
    @Published var score:Int = 0
}
 
struct ButtonOne: View {
    @ObservedObject var settings : UserSettings

    var body: some View {
        HStack {
            Button(action: {
                self.settings.score += 1
                }) {
                    Text("Increase Score")
            }
            Text("In ButtonOne your score is \(settings.score)")
        }
    }
     
}
 
 
struct ContentView: View {
    @ObservedObject var settings = UserSettings()
 
    var body: some View {
        VStack(spacing: 20) {
            Text("In master view your score is \(settings.score)")
            ButtonOne(settings: settings)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

You should not update `@State` variables inside `body`. What do you want to do with your `num`?

i have a two dimensional area that I need to move through the arry at the top level.

i have a two dimensional area that I need to move through the arry at the top level.


Can you explain what you mean ? array ? area ?

There is no trace of this in your code


Did you try the scheme I proposed with a custom button struct ?

I do not understand what you mean by two dimensional area, but moving something does not explain why you need to update `@State` variables in `body`.


`body` may be called at any time when SwiftUI needs it and you should not count something there.


What do you really want to do? There may better and the right solutions than updating `@State` variables.

my apologies. I meant multi dimentional array.


I have used the solutions your provided (You should not update `@State` variables inside `body`) .and hinted.


I created a function outide the body and incremented num


thank you every one

SwiftUI - how to increment @state var integer by one
 
 
Q