UserDefaults

I already searched the internet for this, but I couldn't find a complete answer.


I have an app with favorites. I want to save these favorites after closing the app.


To save the changed data, one can work with Userdefaults.


I have the following code


List {
             Toggle(isOn: $userData.showFavoritesOnly) {
                    Text("show favorites").bold().underline()
                }


In another file


import Foundation

class SettingsViewModel: ObservableObject {
    
    @Published var isOn: Bool = UserDefaults.standard.bool(forKey: "isOn") {
        didSet {
            UserDefaults.standard.set(self.isOn, forKey: "isOn")
        }
    }
}


Any help is appreciated.