UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

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.

4      

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

3      

@twostraws  Site AdminHWS+

@theblixguy Thank you! 🎉

4      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

You are not logged in

Log in or create account
 

Link copied to your pasteboard.