variable in func not working

when I try and change a variable in a function it just gives me
a error that says Cannot find 'textfield' in scope here is the is the code.

import SwiftUI



struct ContentView: View {

    @State var test = "this is a test"





    var body: some View {

       

      Text("Hello")



    }

}

 

func testfunc() {



    

   test = "test"



}





struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

}
Answered by OOPer in 662074022

a error that says Cannot find 'textfield' in scope here is the is the code.

Isn't it Cannot find 'test' in scope?

In your current code (please use Code block), testfunc() is places outside of ContentView,
so its property test is not visible there:
Code Block
struct ContentView: View {
@State var test = "this is a test"
var body: some View {
Text("Hello")
} //<- End of `body`
} //<- End of `ContentView`
func testfunc() {
test = "test"
}


If you want to write a function which modifies some instance property, it needs to be placed inside the same type:
Code Block
struct ContentView: View {
@State var test = "this is a test"
var body: some View {
Text("Hello")
} //<- End of `body`
func testfunc() {
test = "test"
} //<- End of `testfunc()`
} //<- End of `ContentView`



Accepted Answer

a error that says Cannot find 'textfield' in scope here is the is the code.

Isn't it Cannot find 'test' in scope?

In your current code (please use Code block), testfunc() is places outside of ContentView,
so its property test is not visible there:
Code Block
struct ContentView: View {
@State var test = "this is a test"
var body: some View {
Text("Hello")
} //<- End of `body`
} //<- End of `ContentView`
func testfunc() {
test = "test"
}


If you want to write a function which modifies some instance property, it needs to be placed inside the same type:
Code Block
struct ContentView: View {
@State var test = "this is a test"
var body: some View {
Text("Hello")
} //<- End of `body`
func testfunc() {
test = "test"
} //<- End of `testfunc()`
} //<- End of `ContentView`



Thanks. I have no idea why I typed textfield instead of test.
variable in func not working
 
 
Q