How to access variable in separate function

code:

import SwiftUI



struct practise: View {

    @State var value = false

    

    var body: some View {

        Text("Hello, World!")

    }

}



struct practise_Previews: PreviewProvider {

    static var previews: some View {

        practise()

    }

}

func changevalue(){

    //Change Value here

}

How am I able to change the value of 'value', within the change value() function.

Answered by Claude31 in 690608022

Create a button in Practice View calling changeValue.

struct Practise: View {

    @State var value = false

    func changeValue(){

        // Change Value here
        value = !value    // we toggle
       // could call as well:         value.toggle()
    }

    var body: some View {

        Text("Hello, World! \(String(value))")
        Button(action: changeValue) {
            Text("Change")
        }
    }
}

struct practise_Previews: PreviewProvider {

    static var previews: some View {
        Practise()
    }
}
Accepted Answer

Create a button in Practice View calling changeValue.

struct Practise: View {

    @State var value = false

    func changeValue(){

        // Change Value here
        value = !value    // we toggle
       // could call as well:         value.toggle()
    }

    var body: some View {

        Text("Hello, World! \(String(value))")
        Button(action: changeValue) {
            Text("Change")
        }
    }
}

struct practise_Previews: PreviewProvider {

    static var previews: some View {
        Practise()
    }
}
How to access variable in separate function
 
 
Q