繁体   English   中英

如何 Swift 中的 append 字典值

[英]How to append Dictionary value in Swift

我正在尝试将每日数据保存到字典中。 当用户达到他们每日进度的 100% 时,我想将这一天和一个“真实”值添加到字典中。 问题是,当我尝试添加新的键和值时,它会覆盖前一个键和值,因为当天来自同一个变量,该变量会根据当天更改其数据。

let calendarCurrent = Calendar.current
let currentDate = Date()

monthlyDictionary["\(calendarCurrent.component(.day, from: currentDate))"] = "true"
defaults.set(monthlyDictionary, forKey: "monthlyDictionary")

所以字典键是一个等于当天的变量,值是“真”

您发布的代码总是用字典替换键monthlyDictionary的内容。 您创建的字典使用当月的当天作为键和“true”的值。

今天是 1 月 19 日,因此如果您今天运行该代码,它将在 UserDefaults 中创建一个条目,其中包含键monthlyDictionary和值["19": "true"] 明天它将用包含值["19": "true"]的新字典替换键monthlyDictionary中的值

如果你想 append 每天在你的字典中添加一个新条目,你需要阅读现有字典 append 一个值,然后重新编写它:

let calendarCurrent = Calendar.current
let currentDate = Date()

var oldMonthlyDictionary = [AnyHashable:Any]()
oldMonthlyDictionary = defaults.object(forKey: "monthlyDictionary") as? Dictionary else {
   print("dictionary not found. Creating empty dictionary")
}//Add this line

//Add a new key/value pair to your dictionary and re-save it.
oldMonthlyDictionary["\(calendarCurrent.component(.day, from: currentDate))"] = "true"
defaults.set(oldMonthlyDictionary, forKey: "monthlyDictionary")

编辑:

请注意,如果您在给定的日历日内多次运行此代码,它将在每次后续运行时覆盖当前日期的前一个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM