TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Day 37: Making changes permanent with UserDefaults

Forums > 100 Days of SwiftUI

I've finished this app completely, and everything work perfectly... execpt none of the data will save. I've been looking for my error for almost two hours, but I can't find anything. If someone could help me out that would be amazing!

Project Files

3      

@Published var items = [ExpenseItem]() {
        didSet {
            let encoder = JSONEncoder()

            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            } else {
                fatalError()
            }
        }
    }

It looks like your saving via UserDefaults is taking place within the didSet observer of a @Published property. Make sure you have upgraded to Xcode 11.5, as it fixes an issue where didSet property observers would not fire on @Published properties.

4      

Xcode 11.5 is still in beta, but it's very helpful to know it's not an error on my behalf. Thanks!

I'll will revisit the project when 11.5 is released and update this post. More to come.

4      

I just tested the new Xcode 11.5 update and UserDefaults is working again!

4      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.