Search code examples
swiftuserdefaults

How to add to a number currently stored in user defaults Swift 4


I want the user to be able to enter a new number and it will be added to what is currently saved in UserDefaults and then save that combined number in user defaults. Anyone have any idea how to do this? Thanks!

Code:

    let typeHoursInt = Double(typeHours.text!)!
    let typePayInt = Double(typePay.text!)!
    totalMade.text = String(typeHoursInt * typePayInt)

    UserDefaults.standard.set(totalMade.text, forKey: "savedMoney")

Solution

  • This does what you ask. You should store your totalMade variable in User Defaults as a Double, not a String. See below:

    // your original code
    let typeHoursInt = Double(typeHours.text!)!
    let typePayInt = Double(typePay.text!)!
    
    let total = typeHoursInt * typePayInt
    
    totalMade.text = String(total)
    
    // saving original value in User Defaults
    UserDefaults.standard.set(total, forKey: "savedMoney")
    
    // retrieving value from user defaults
    var savedMoney = UserDefaults.standard.double(forKey: "savedMoney")
    
    // adding to the retrieved value
    savedMoney = savedMoney + 5.0
    
    // resaving to User Defaults
    UserDefaults.standard.set(savedMoney, forKey: "savedMoney")