【问题标题】:How to append Dictionary value in Swift如何在 Swift 中附加字典值
【发布时间】:2021-04-24 01:48:44
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: swift dictionary append


    【解决方案1】:

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

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

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

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

    编辑:

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

    【讨论】:

    • 感谢您的快速回复。我尝试了此代码,但出现以下错误:“'Any' 类型的值?没有下标” 在该行:oldMonthlyDictionary["(calendarCurrent.component(.day, from: currentDate))"] = "true"
    • var oldMonthlyDictionary = defaults.object(forKey: "monthlyDictionary") as?字典
    • defaults.object(...) 返回 Any 类型,因为它不知道类型 - 您需要将类型转换为它应该是的任何类型。从那里,您可以下标
    • 我应该知道最好不要在不编译的情况下在 SO 线程中键入答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2015-06-10
    • 1970-01-01
    • 2015-02-03
    • 2021-02-22
    • 2021-05-17
    • 2014-10-13
    相关资源
    最近更新 更多