Change textfield to double with button click

Viewed 31

Im trying to use a textfield to take a string and then when the save button is clicked, it saves that value typed as a double using CoreData. But it keeps giving an error stating that "Value of optional type 'Double?' must be unwrapped to a value of type 'Double'" Any ideas?

  1. hoursSlept is the variable the textfield is bonded to
  2. newSleep is the variable for the struct SleepModel (my sleep type)
  3. Im taking the textfield value and trying to force into a double using Double() with a new variable. But it keeps giving the error.
Button(action: {
                  var hoursSleptDouble = Double(hoursSlept)
                  newSleep!.hoursSlept = hoursSleptDouble
                  
                  if newSleep != nil {
                      coreDataViewModel.saveRecord(sleepModel: newSleep!) {
                          print("Success")
                      }
                  }
              })
               {
                    Capsule()
                        .foregroundColor(Color.green)
                        .frame(height: 44)
                        .overlay(Text("Add Entry").foregroundColor(Color.white).bold())
                }.padding()
1 Answers

Based on someones advise I switched the code up a bit. I initialized the sleepModel inside of a function which is called when the button is pushed. Then inside that function I create the doubles from the user input textfields. That way there are no optionals!

Related