Reputation: 4180
I have defined the following dictionary:
class TimeToEatTrackerViewModel: ObservableObject {
@Published var mealAndStatus: [String: String] =
UserDefaults.standard.dictionary(forKey: "mealAndStatus") as? [String: String] ?? ["Breakfast": "initial", "Snack": "notSet", "Lunch": "notSet", "Snack2": "notSet", "Dinner": "notSet"] {
didSet {
UserDefaults.standard.set(self.mealAndStatus, forKey: "mealAndStatus")
}
}
}
and I'm calling it in the view:
struct ContentView: View {
@ObservedObject var eatTracker = TimeToEatTrackerViewModel()
var body: some View {
VStack {
Button(action: {
self.eatTracker.mealAndStatus["Breakfast"] = "done"
}){
Text(String(self.eatTracker.mealAndStatus["Breakfast"]!))
}
}
}
}
While the execution happens as expected, the values are not being stored. When I close the app and come back, the new values are not there, why?
Thanks
Upvotes: 1
Views: 54
Reputation: 257711
Changing property wrapper content value does not trigger didSet
, at least for now, Xcode 11.4, so the solution is
Button(action: {
var tmp = self.eatTracker.mealAndStatus
tmp["Breakfast"] = "done"
self.eatTracker.mealAndStatus = tmp
}){
Upvotes: 1