问题
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")
回答1:
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")
回答2:
Don't save strings to userDefaults. Save numbers.
Then:
Read the value from defaults.
Add your new value to the newly read value
Save the new sum back to defaults.
回答3:
Below you'll find "8" and "20", which are replacements for typeHours.text and typePay.text respectively.
UserDefaults.standard.set(535, forKey: "savedMoney")
if let typeHoursInt = Int("8"), let typePayInt = Int("20") {
let totalMade = typeHoursInt * typePayInt
let newTotal = UserDefaults.standard.integer(forKey: "savedMoney") + totalMade
UserDefaults.standard.set(newTotal, forKey: "savedMoney")
}
来源:https://stackoverflow.com/questions/49180542/how-to-add-to-a-number-currently-stored-in-user-defaults-swift-4