Every time I press the button an instance of the School struct is created. I want to show that change on the screen but the button doesn't update. What am I missing to make it work?
import SwiftUI
struct School {
static var studentCount = 0
static func add(student: String) {
print("\(student) joined the school.")
studentCount = 1
}
}
struct ReviewClosuresAndStructs: View {
@State private var test = School.studentCount
var body: some View {
VStack {
Button(action: {
School.add(student: "Tyler")
}, label: {
Text("Press me. \n Students: \(test)")
})
}
}
}
struct ReviewClosuresAndStructs_Preview: PreviewProvider {
static var previews: some View {
ReviewClosuresAndStructs()
}
}
CodePudding user response:
struct School {
var studentCount = 0 // <= here
mutating func add(student: String) { // <= here
print("\(student) joined the school.")
studentCount = 1
}
}
struct ReviewClosuresAndStructs: View {
@State private var test = School() // <= here
var body: some View {
VStack {
Button(action: {
test.add(student: "Tyler")
}, label: {
Text("Press me. \n Students: \(test.studentCount)") // <= here
})
}
}
}