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

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.