BLACK FRIDAY: Save 50% on all books and bundles! >>

Day 37 didSet on Items no longer works - so the item is not getting stored

Forums > SwiftUI

Maybe this did work in the past, but I'm on XCode Version 11.4.1 (11E503a) and the didSet no longer runs on the items property when a new item is added:

class Expenses: ObservableObject {

    @Published var items: [ExpenseItem] {
        didSet {
            let encoder = JSONEncoder()
            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() { ... }

    }

So I had to move the encoder code to the point where the item is saved instead :

Button("Save") {
                        if let actualAmount = Int(self.amount) {
                            let item = ExpenseItem(name: self.name,
                                                   type: self.type,
                                                   amount: actualAmount)
                            self.expenses.items.append(item)
                            let encoder = JSONEncoder()
                            if let encoded = try? encoder.encode(self.expenses.items) {
                                UserDefaults.standard.set(encoded, forKey: "Items")
                            }
                            self.presentationMode.wrappedValue.dismiss()
                        }
}

That's a workaround, but I dont get why didSet no longer works

   

It's a known bug when using a didSet property observer on a @Published property. The bug was introduced with Swift 5.2 and has already been fixed but not yet released.

1      

Just an update - the fix is now available in Xcode 11.5 beta.

   

@twostraws  Site AdminHWS+

@theblixguy Thank you! 🎉

1      

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.