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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.