如何添加到当前存储在用户默认值 Swift 中的号码 4

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

我希望用户能够输入一个新号码,它将添加到当前保存在 UserDefaults 中的号码中,然后将该组合号码保存在用户默认值中。任何人都知道如何做到这一点?谢谢!

代码:

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

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

不要将字符串保存到 userDefaults。保存号码。

然后:

  1. 从默认值读取值。

  2. 将您的新值添加到新读取的值

  3. 将新金额保存回默认值。

下面是 "8""20",它们是 [=21 的替代品=]typePay.text

  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")
  }

这就是你所要求的。您应该将 totalMade 变量作为 Double 而不是 String 存储在 User Defaults 中。见下文:

// 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")