1

I have a problem when trying to save array of strings into the UserDefaults. I have a simple ObservableObject with one property:

class AppManagerModel: ObservableObject {
    @Published var userData = UserDefaults.standard.array(forKey: "userData") as? [String] ?? [String]()
}

Then when i try to update that data from the view

UserDefaults.standard.set(appManagerModel.userData.append("Test"), forKey: "userData")

I get the following error- "Attempt to insert non-property list object () for key userData"

1
  • append returns void. Append then set. Commented May 16, 2021 at 14:01

1 Answer 1

1

Array.append returns Void . You need to append to the array then set.

class AppManagerModel: ObservableObject {
    @Published var userData = UserDefaults.standard.array(forKey: "userData") as? [String] ?? [String]()
    
    func addUserData(_ data: String) {
        userData.append(data)
        UserDefaults.standard.set(userData, forKey: "userData")
    }
}

Keep your persistence logic hidden in AppManagerModel rather than putting it in your View.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.