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

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.