I've got the following code, which seems very simple.
import SwiftUI
struct Tester : View
{
@State var blah : String = "blah"
func setBlah(_ val : String) {
blah = val
}
var body: some View {
Text("text")
}
}
var test = Tester()
test.setBlah("blee")
print(test.blah)
I would normally expect to see the final print statement display "blee", but it is "blah" -- the variable never changed. If I pass blah into another view via a binding, I am able to change the value of blah there. Any insight here would be appreciated -- including rtfm, if you can point me to the right manual -- I have looked, and haven't found an answer.
Edit: after reading @jnpdx 's answer, I have a slightly different version, but it still doesn't work -- I'm not worried about this specific code working, but trying to understand the magic that @jnpdx refers to, in terms of how @State works, and why a binding passed to another view is able to modify the original @State variable, while I am unable to within the struct itself. I am guessing there is some part of SwiftUI that needs to be instantiated that the @State property's communicate with in order to store the variables outside of the struct, as the apple documentation says. New version follows:
import Foundation
import SwiftUI
struct Tester : View
{
@State var blah : String
func setBlah(_ val : String) {
$blah.wrappedValue = val
}
var body: some View {
Text("smoe text")
}
}
var test = Tester(blah: "blah")
test.setBlah("blee") // expect to see blee printed, but get nil instead
print(test.blah)
Thanks :)
View'sStatefrom the parent and modify it. Plus, yourViewisn't in a hierarchy and so who knows if SwiftUI is doing anything to manage the state (my guest is that it isn't). Any attempt you have to reach in and modify@Statelike this will be unreliable at best and flat out not work at worst.