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

Cannot assign to property: 'self' is immutable

Forums > SwiftUI

I am creating a page settingView for saving userdata where I call a class with @ObservedObject. And I also made some func in the settingView page for load and save the userdata. But there I get the error "Cannot assign to property: 'self' is immutable in SettingView". How can I solve this.

Here is a part of my class

class UserData: ObservableObject, Codable {
    @Published var name = ""
    @Published var firstname = ""
    @Published var email = ""
}

And here a part of the SettingView

struct SettingsView: View {
    @ObservedObject var userdata = UserData()

var body: some View {

        NavigationView{
            Form {
                Section(header: Text("User")){
                    TextField("Name", text: $userdata.name)
                    TextField("Firstname", text: $userdata.firstname)
                    TextField("Email...", text: $userdata.email)
                   //more code
                }
                Section{
                    Button(action: {
                        self.saveData()
                        self.showingAlert = true
                    }){
                        Text("Save")
                    }
            }
        }

        .onAppear(perform: {
            self.loadData()
        })
    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

    func loadData() {
        let filename = getDocumentsDirectory().appendingPathComponent("SavedData")

        do {
            let data = try Data(contentsOf: filename)
            userdata = try JSONDecoder().decode(UserData.self, from: data) //<-- error on userdata
            print("File is loaded")
        } catch {
            print("Unable to load saved data.")
        }
    }
}

2      

The problem is that by changing userdata within a function called from body, you are trying to mutate the SettingsView struct from within body which, as a computed property with a non-mutating getter, cannot mutate the struct.

Change your @ObservedObject to @StateObject and load the data in your SettingsView initializer. I think that should fix it. (NOTE: I haven't actually tried any code to back this up; I'm flying by the seat of my pants here!)

2      

Hi thanks for your advice. But I made a @state var NewUserData and used that in my LoadData and then I set all my userdata equal to NewUserData. Now I can load the data on appear.

2      

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.