New to Swift and am trying to use structs where I can hold values. When I try to bind them with a TextField it doesn't update the actual variable. What is wrong?
@State var final = finalBluePrint()
var body : some View {
NavigationView {
VStack {
TextField("Current Grade", value: $final.currentGrade, format: .number).keyboardType(.decimalPad);
TextField("Desired Grade", value: $final.desiredGrade, format: .number).keyboardType(.decimalPad);
TextField("Final Weight", value: $final.finalWeight, format: .number).keyboardType(.decimalPad);
Text(final.currentGrade, format: .number);
Text(final.finalNeededGrade, format: .number);
}
@State var currentGrade: Double = 5;
@State var desiredGrade : Double = 0;
@State var finalWeight : Double = 0;
var finalNeededGrade : Double {
let desiredGrade = self.desiredGrade;
let currentGrade = self.currentGrade;
let finalWeight = self.finalWeight;
let finalNeededGrade = (desiredGrade - currentGrade * (100 - finalWeight)) / finalWeight;
return finalNeededGrade
}
Thank you!
class FinalBluePrint: ObservableObject {
@Published var currentGrade: Double = 5;
@Published var desiredGrade : Double = 0;
@Published var finalWeight : Double = 0;
var finalNeededGrade : Double {
let desiredGrade = self.desiredGrade;
let currentGrade = self.currentGrade;
let finalWeight = self.finalWeight;
let finalNeededGrade = (desiredGrade - currentGrade * (100 - finalWeight)) / finalWeight;
return finalNeededGrade
}
}
struct ContentView: View {
@StateObject var final = FinalBluePrint()
var body : some View {
NavigationView {
VStack {
TextField("Current Grade", value: $final.currentGrade, format: .number).keyboardType(.decimalPad);
TextField("Desired Grade", value: $final.desiredGrade, format: .number).keyboardType(.decimalPad);
TextField("Final Weight", value: $final.finalWeight, format: .number).keyboardType(.decimalPad);
Text(final.currentGrade, format: .number);
Text(final.finalNeededGrade, format: .number);
}
}
}
}