I ran in to some problems and wrote some basic variant to show the problem:
import SwiftUI
struct PersonStruct {
// Requires @State because self.name is immutable otherwise
@State var name:String
init (_ name: String) { self.name = name }
func changeName(_ name: String) {
self.name = name
print (self.name)
}
}
class PersonClass {
var name:String
init (_ name: String) { self.name = name }
func changeName(_ name: String) {
self.name = name
print (self.name)
}
}
struct ContentView: View {
var person1:PersonStruct = PersonStruct("Peter S.")
var person2:PersonClass = PersonClass("Peter C.")
var body: some View {
VStack {
Text(person1.name)
.padding()
Text(person2.name)
.padding()
Button("Change name") {
person1.changeName("Trevor")
person1.name = "Trevor"
person2.changeName("Trevor")
person2.name = "Trevor"
print("---")
print (person1.name)
print (person2.name)
}
.padding()
}
.font(.title)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The person variables behave different, pressing the button changes the name of person2 from "Peter C" to Trever - as seen by "print" in the console. But the name of person1 will not be changed, it stays at "Peter S." ...
So, the struct does not seem to work at all.
And in both cases, the Text outputs in the View will both not change - "Peter C" and "Peter S" stay visible.
Why does the content from person1 not change? I even used both the function "changeName()" and also tried to set the name directly. To no avail :-(
@Statein a non SwiftUI struct, I.e one that doesn’t conform toView. You should on the other hand use@Statefor both your properties inContentView. Fix that and come back if you still have an issue