Search code examples
iosswiftnsuserdefaults

Adding up entered value with an existing value in swift


I have a text field where I can enter a double and it will be displayed on a label in the 2nd view controller. This value will be saved using UserDefaults. I am struggling to find what to do, to be able to then use this saved value and increase it with a new value entered in the text field. i.e 1st time I enter 5; label displays 5. 2nd time I enter 3; label displays 8.

I tried to use the below if function, but this has not worked. When I enter a value for the 2nd time the label value goes back to 0, if then enter a value again, label is updated with the value entered.

func saveOne() {
    UserDefaults.standard.set(weekOneTotal, forKey: "WEEKONE")
    secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))
}

func addCorrectSpend () {
    guard let addAmount = convertAmount(input: enterField.text!) else {
        print("Invalid amount")
        return
    }

    if UserDefaults().double(forKey: "WEEKONE") == 0 {    
        weekOneTotal += addAmount  
        secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))    
        saveOne()
    }

    else if UserDefaults().double(forKey: "WEEKONE") > 0 {
        let defaultOne = UserDefaults.standard
        defaultOne.set(defaultOne.double(forKey: "WEEKONE")+addAmount, forKey: "WEEKONE")
        secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))
        saveOne()
    }
}

Solution

  • To answer (quickly) why this is happening: You are setting the initial value in UserDetails.standard, which is correct, but then you are updating the value in a new UserDefaults() object each time.

    You can also pare down your code a little bit as there is some unnecessary stuff in there. Ultimately you just need to add the new value to the existing value, so you don't really need to check if the existing value == 0. Here is an example of how I may refactor the above code:

    func addCorrectSpend() {
      guard let addAmount = convertAmount(input: enterField.text!) else {
        print("Invalid amount")
        return
      }
      //Get the existing total (will be 0 if none)
      let weekOneAmount = UserDefaults.standard.double(forKey: "WEEKONE")
      //Add the existing total to the new amount from your textField
      let weekOneTotal = weekOneAmount + addAmount
      //Update UserDefaults.standard to the new value
      UserDefaults.standard.set(weekOneTotal, forKey: "WEEKONE")
      //Set the text
      secondScreen.weekOneText = "\(weekOneTotal)"
    }