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

删除回忆录丶 提交于 2019-12-14 04:04:13

问题


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:

  1. Read the value from defaults.

  2. Add your new value to the newly read value

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!