Reputation: 47
I'm trying to save daily data to a Dictionary. When the user reaches 100% of their daily progress I want to add that day and a "true" value with it into a Dictionary. The problem is, when I try to add a new Key and Value it overrides the previous one because the current day is coming from the same variable which changes it's data depending on the day.
let calendarCurrent = Calendar.current
let currentDate = Date()
monthlyDictionary["\(calendarCurrent.component(.day, from: currentDate))"] = "true"
defaults.set(monthlyDictionary, forKey: "monthlyDictionary")
So the Dictionary Key would be a variable equal to the current day and the value would be "true"
Upvotes: 0
Views: 666
Reputation: 131436
The code you posted always replaces the contents of a key monthlyDictionary
with a dictionary. The dictionary you create uses the current day of the month as a key and the value of "true".
Today is 19 January, so if you run that code today, it will create an entry in UserDefaults with the key monthlyDictionary
and the value of ["19": "true"]
. Tomorrow it will replace the value at the key monthlyDictionary
with a new dictionary that contains the value ["19": "true"]
If you want to append a new entry to your dictionary each day, you'll need to read the existing dictionary, append a value, and then re-write it:
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")
Note that if you run this code more than once in a given calendar day, it will overwrite the previous value for the current day on each subsequent run.
Upvotes: 1