简体   繁体   中英

Change textfield to double with button click

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()

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM